未验证 提交 7358b18e 编写于 作者: O openharmony_ci 提交者: Gitee

!13629 [翻译完成】#I63HUE

Merge pull request !13629 from Annie_wang/PR11892B
# Crypto Framework
# @ohos.security.cryptoFramework (Crypto Framework)
The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations.
The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations.
> **NOTE**
>
>
> The initial APIs of this module are supported since API version 9.
## Modules to Import
......@@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Default Value | Description |
| --------------------------------------| -------- | -------------------------|
| INVALID_PARAMS | 401 | Invalid parameters. |
| NOT_SUPPORT | 801 | This operation is not supported. |
| ERR_OUT_OF_MEMORY | 17620001 | Memory error. |
| ERR_RUNTIME_ERROR | 17620002 | Runtime error. |
| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. |
| Name | Value | Description |
| ------------------------------------- | -------- | ---------------------------- |
| INVALID_PARAMS | 401 | Invalid parameters. |
| NOT_SUPPORT | 801 | Unsupported operation. |
| ERR_OUT_OF_MEMORY | 17620001 | Memory error. |
| ERR_RUNTIME_ERROR | 17620002 | Runtime error. |
| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. |
## DataBlob
Defines a binary data array.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | Yes | Yes | Data. |
| Name| Type | Readable| Writable| Description |
| ---- | ---------- | ---- | ---- | ------ |
| data | Uint8Array | Yes | Yes | Data.|
## cryptoFramework.createMac
......@@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations.
| ---- | --------------------------------------- |
| Mac | [Mac](#mac) instance created.|
**Error codes**
| ID| Error Message |
| -------- | ------------------ |
| 17620001 | memory error |
**Example**
```javascript
......@@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
// Set algName based on the algorithm supported.
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
......@@ -70,7 +80,7 @@ try {
Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac).
### **Attributes**
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
......@@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| key | SymKey | Yes | Shared symmetric key. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------ |
| key | SymKey | Yes | Shared symmetric key.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
......@@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
});
```
### init
init(key : SymKey) : Promise\<void>;
......@@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t
**Return value**
| Type | Description |
| --------------- | ------------ |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -149,9 +169,7 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
......@@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| input | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| input | DataBlob | Yes | Data to pass in.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
......@@ -190,7 +216,6 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
......@@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| input | DataBlob | Yes | Message to pass in.|
| input | DataBlob | Yes | Data to pass in.|
**Return value**
| Type | Description |
| --------------- | ----------- |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
......@@ -237,14 +272,11 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
......@@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => {
```
### doFinal
doFinal(callback : AsyncCallback\<DataBlob>) : void;
......@@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------- |
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -284,7 +323,6 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
......@@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result.
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Type | Description |
| ------------------ | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -339,7 +384,6 @@ try {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
......@@ -375,6 +419,12 @@ Obtains the MAC length, in bytes.
| ------ | ------------------------- |
| number | MAC length obtained.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -387,7 +437,6 @@ try {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
......@@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => {
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
AlertDialog.show({message: "MAC len: " + macLen});
console.error("MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
......@@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations.
| ---- | ------------------------------------- |
| Md | [Md](#md) instance created.|
**Error codes**
| ID| Error Message |
| -------- | ------------------ |
| 17620001 | memory error |
**Example**
```javascript
......@@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
// Set algName based on the algorithm supported.
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
......@@ -448,27 +504,34 @@ try {
Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd).
### **Attributes**
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | -------------------- |
| algName | string | Yes | No | Digest algorithm to use.|
| algName | string | Yes | No | Digest algorithm.|
### update
update(input : DataBlob, callback : AsyncCallback\<void>) : void;
Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result.
Updates the message digest data. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------ |
| input | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| input | DataBlob | Yes | Data to pass in.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
......@@ -495,20 +558,26 @@ md.update(blob, (err,) => {
update(input : DataBlob) : Promise\<void>;
Updates the message digest data with the message passed in. This API uses a promise to return the result.
Updates the message digest data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| input | DataBlob | Yes | Message to pass in.|
| input | DataBlob | Yes | Data to pass in.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------- |
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result.
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Type | Description |
| ------------------ | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -622,7 +705,13 @@ Obtains the message digest length, in bytes.
| Type | Description |
| ------ | ------------------------ |
| number | Message digest length obtained. |
| number | Message digest length obtained.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17630001 | crypto operation error |
**Example**
......@@ -645,7 +734,7 @@ promiseMdUpdate.then(() => {
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
AlertDialog.show({message: "MD len: " + mdLen});
console.error("MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
......@@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds.
| ------ | --------------------------------------------- |
| Random | [Random](#random) instance created.|
**Error codes**
| ID| Error Message |
| -------- | ------------ |
| 17620001 | memory error |
**Example**
```javascript
......@@ -679,7 +774,7 @@ try {
## Random
Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom).
Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom).
### generateRandom
......@@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------- |
| len | number | Yes | Length of the random number to generate.|
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.|
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | -------------------- |
| len | number | Yes | Length of the random number to generate.|
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
......@@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| len | number | Yes | Length of the random number to generate.|
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Type | Description |
| ------------------ | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 17620001 | memory error |
| 17630001 | crypto operation error |
**Example**
```javascript
......@@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => {
### setSeed
setSeed(seed : DataBlob, callback : AsyncCallback\<void>) : void;
setSeed(seed : DataBlob) : void;
Sets a seed. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------ |
| seed | DataBlob | Yes | Seed to set. |
| callback | AsyncCallback\<void\> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| seed | DataBlob | Yes | Seed to set.|
**Error codes**
| ID| Error Message |
| -------- | ----------------- |
| 17620001 | memory error |
**Example**
......@@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => {
console.error("[Callback] err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
rand.setSeed(randData, (err1, data) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: setSeed success");
}
});
try {
rand.setSeed(randData);
} catch (error) {
console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message);
}
}
});
```
### setSeed
setSeed(seed : DataBlob) : Promise\<void>;
Sets a seed. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| seed | DataBlob | Yes | Seed to set.|
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var promiseGenerateRand = rand.generateRandom(12);
promiseGenerateRand.then(randData => {
console.error("[Promise]: rand result: " + randData.data);
var promiseSetSeed = rand.setSeed(randData);
return promiseSetSeed;
}).then(() => {
console.error("[Promise]: setSeed success");
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## ParamsSpec
Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required.
Defines the parameters used for encryption and decryption. <br>For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2).
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. <br/>Options:<br>- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.<br>- **GcmParamsSpec**: applicable to the GCM mode.<br>- **CcmParamsSpec**: applicable to the CCM mode. |
| Name | Type | Readable| Writable| Description |
| -------- | ------ | ---- | ---- | ----------------------- |
| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:<br>- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.<br>- **GcmParamsSpec**: applicable to the GCM mode.<br>- **CcmParamsSpec**: applicable to the CCM mode.|
> **NOTE**
> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**.
## IvParamsSpec
Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2).
Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. <br>**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. <br/>Options:<br>- AES CBC, CTR, OFB, or CFB mode: 16-byte IV<br>- 3DES CBC, OFB or CFB mode: 8-byte IV |
| Name| Type | Readable| Writable| Description |
| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:<br>- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV<br>- 3DES CBC,|OFB, or |CFB mode: 8-byte IV|
> **NOTE**
> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## GcmParamsSpec
Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2).
Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. <br>**GcmParamsSpec** applies to the GCM mode.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.|
| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.|
| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.<br>When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.|
| Name | Type | Readable| Writable| Description |
| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. |
| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. |
| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.<br>When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). |
> **NOTE**
> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## CcmParamsSpec
Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2).
Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. <br>**CcmParamsSpec** applies to the CCM mode.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | -------- | ---- | ---- | -------------------------------|
| Name | Type | Readable| Writable| Description |
| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. |
| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. |
| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.<br>When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.|
| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.<br>When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).|
> **NOTE**
> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## CryptoMode
......@@ -877,22 +971,22 @@ Enumerates the cryptographic operations.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Value | Description |
| ------------ | -------- | -------------------------------- |
| ENCRYPT_MODE | 0 | Encryption. |
| DECRYPT_MODE | 1 | Decryption. |
| Name | Value | Description |
| ------------ | ---- | ---------------- |
| ENCRYPT_MODE | 0 | Encryption.|
| DECRYPT_MODE | 1 | Decryption.|
## Key
Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator.
Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. <br>Keys can be generated by a key generator.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | Yes | No | Format of the key.|
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
......@@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously
**Return value**
| Type |Description |
| ------- | ----------- |
| Type | Description |
| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
import cryptoFramework from "@ohos.security.cryptoFramework"
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data));
```
## SymKey
Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator).
Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. <br>Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator).
### clearMem
clearMem() : void
Clears the keys from the memory. This API returns the result synchronously.
Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
import cryptoFramework from "@ohos.security.cryptoFramework"
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let encodedKey = key.getEncoded();
console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content.
console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content.
key.clearMem();
encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s.
......@@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a
## PubKey
Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**.
Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. <br>Public keys can be generated by an **AsyKeyGenerator**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | Yes | No | Format of the key.|
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
......@@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The
**Return value**
| Type |Description |
| ------- | ----------- |
| Type | Description |
| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here.
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data));
```
## PriKey
Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**.
Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. <br>Private keys can be generated by an **AsyKeyGenerator**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | Yes | No | Format of the key.|
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
......@@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The
**Return value**
| Type |Description |
| ------- | ----------- |
| Type | Description |
| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data));
```
### clearMem
clearMem() : void
Clears the keys from the memory. This API returns the result synchronously.
Clears the keys in the memory. This API returns the result synchronously.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
key.clearMem();
```
## KeyPair
Defines an asymmetric key pair, which includes a public key and a private key. <br>Asymmetric key pairs can be generated by the **AsyKeyGenerator**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ------------ |
| priKey | [PriKey](#prikey) | Yes | No | Private key. |
| pubKey | [PubKey](#pubkey) | Yes | No | Public key. |
## cryptoFramework.createSymKeyGenerator
createSymKeyGenerator(algName : string) : SymKeyGenerator
Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).
Creates a **symKeyGenerator** instance based on the specified algorithm. <br>For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ----------------------------- |
| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.<br>For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).|
**Return value**
| Type | Description |
| Type | Description |
| ----------------------------------- | -------------------------- |
| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.|
| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.|
**Example**
......@@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
## SymKeyGenerator
Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
Provides APIs for using the **symKeyGenerator**. <br>Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ------------------------------ |
| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.|
### generateSymKey
generateSymKey(callback : AsyncCallback\<SymKey>) : void
Generates a key randomly. This API uses an asynchronous callback to return the result.
Generates a key randomly. This API uses an asynchronous callback to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). <br>**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------- | ---- | ------------------- |
| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| -------- | ------------- |
| 17620001 | memory error. |
**Example**
......@@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
symKeyGenerator.generateSymKey((err, symKey) => {
if (err) {
console.error('Failed to generate symKey');
return;
}
console.log('Generate symKey success, algName: ' + symKey.algName);
if (err) {
console.error(`Generate symKey failed, ${err.code}, ${err.message}`);
} else {
console.info(`Generate symKey success, algName: ${symKey.algName}`);
}
})
```
......@@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => {
generateSymKey() : Promise\<SymKey>
Generates a key randomly. This API uses a promise to return the result.
Generates a key randomly. This API uses a promise to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). <br>**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Type | Description |
| --------------------------- | --------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
**Error codes**
| ID| Error Message |
| -------- | ------------- |
| 17620001 | memory error. |
**Example**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
symKeyGenerator.generateSymKey().then((symKey) => {
console.log('Generate symKey success, algName:' + symKey.algName);
symKeyGenerator.generateSymKey()
.then(symKey => {
console.info(`Generate symKey success, algName: ${symKey.algName}`);
}, error => {
console.error(`Generate symKey failed, ${error.code}, ${error.message}`);
})
```
......@@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => {
convertKey(key : DataBlob, callback : AsyncCallback\<SymKey>) : void
Converts a key. This API uses an asynchronous callback to return the result.
Converts data into a symmetric key. This API uses an asynchronous callback to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------- | ---- | ---------------------- |
| key | [DataBlob](#datablob) | Yes | Key to convert. |
| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| key | [DataBlob](#datablob) | Yes | Data to convert. |
| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------------------------------- |
| 17620001 | memory error. |
**Example**
......@@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() {
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
symKeyGenerator.convertKey(keyMaterial, (err, symKey) => {
if (err) {
console.error('Failed to convert symKey');
return;
}
console.log('Convert symKey success, algName:' + symKey.algName);
symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => {
if (err) {
console.error(`Convert symKey failed, ${err.code}, ${err.message}`);
} else {
console.info(`Convert symKey success, algName: ${symKey.algName}`);
}
})
```
......@@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => {
convertKey(key : DataBlob) : Promise\<SymKey>
Converts a key. This API uses a promise to return the result.
Converts data into a symmetric key. This API uses a promise to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| key | [DataBlob](#datablob) | Yes | Key to convert.|
| Name| Type | Mandatory| Description |
| ---- | --------------------- | ---- | -------------------- |
| key | [DataBlob](#datablob) | Yes | Data to convert.|
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Type | Description |
| --------------------------- | --------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------------------------- |
| 17620001 | memory error. |
**Example**
```js
......@@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() {
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
symKeyGenerator.convertKey(keyMaterial).then((symKey) => {
console.log('Convert symKey success, algName:' + symKey.algName);
symKeyGenerator.convertKey(keyMaterialBlob)
.then(symKey => {
console.info(`Convert symKey success, algName: ${symKey.algName}`);
}, error => {
console.error(`Convert symKey failed, ${error.code}, ${error.message}`);
})
```
## cryptoFramework.createAsyKeyGenerator
createAsyKeyGenerator(algName : string) : AsyKeyGenerator
Creates an **AsyKeyGenerator** instance based on the specified algorithm.
**System capability**: SystemCapability.Security.CryptoFramework
......@@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm.
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | -------------------------------- |
| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.|
**Return value**
| Type | Description |
| --------------- | -------------------------- |
| Type | Description |
| --------------- | ---------------------------- |
| asyKeyGenerator | **AsyKeyGenerator** instance created.|
**Example**
......@@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------------------------|
| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. |
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | -------------------------------- |
| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.|
### generateKeyPair
generateKeyPair(callback : AsyncCallback\<KeyPair>) : void;
Generates a key pair randomly. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------- | ---- | ---------------------------- |
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------ |
| callback | AsyncCallback\<KeyPair> | Yes | Callback invoked to return the key pair obtained.|
**Example**
......@@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => {
### generateKeyPair
generateKeyPair() : Promise\<KeyPair>
Generates a key pair randomly. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Type | Description |
| ----------------- | --------------------------------- |
| Promise\<KeyPair> | Promise used to return the key pair generated.|
**Example**
......@@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => {
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\<KeyPair\>) : void
Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**.
Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------- | ---- | ---------------------------- |
| pubKey | DataBlob | No | Public key material to convert. |
| priKey | DataBlob | No | Private key material to convert. |
| Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ------------------------------ |
| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. |
| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. |
| callback | AsyncCallback\<KeyPair> | Yes | Callback invoked to return the key pair obtained.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here.
let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here.
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
if (err) {
......@@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair>
Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**.
Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| pubKey | DataBlob | No | Public key material to convert. |
| priKey | DataBlob | No | Private key material to convert. |
| Name | Type | Mandatory| Description |
| ------ | -------- | ---- | ---------------- |
| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.|
| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.|
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Type | Description |
| ----------------- | --------------------------------- |
| Promise\<KeyPair> | Promise used to return the key pair generated.|
**Example**
......@@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here.
let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here.
let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey);
keyGenPromise.then( keyPair => {
console.info("convertKey success.");
......@@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => {
**Key Conversion**
- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage.
- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage.
- The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format.
- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in.
- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in.
## cryptoFramework.createCipher
createCipher(transformation : string) : Cipher
Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).
Creates a [Cipher](#cipher) instance based on the specified algorithm. <br>For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------ | -------- | ------------------------------------------------------------ |
| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.|
| Name | Type | Mandatory| Description |
| -------------- | ------ | ---- | ------------------------------------------------------------ |
| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.<br>For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). |
> **NOTE**
> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed. <br>You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length.
> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same.
**Return value**
| Type | Description |
| ------ | ------------------------ |
| Type | Description |
| ----------------- | ------------------------ |
| [Cipher](#cipher) | [Cipher](#cipher) instance created.|
**Example**
......@@ -1414,39 +1579,51 @@ try {
console.info(`cipher algName: ${cipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
```
## Cipher
Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations).
Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. <br>For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data).
A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process.
- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation.
- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable | Writable | Description |
| ------- | ------ | -------- | ----------- | ---------------------------- |
| algName | string | Yes | No | Algorithm to use.|
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| algName | string | Yes | No | Algorithm.|
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\<void>) : void
Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result.
Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------ | ------- | ------------------------ |
| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
| key | [Key](#key) | Yes | Key for encryption or decryption. |
| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
| key | [Key](#key) | Yes | Key for encryption or decryption. |
| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| -------- | --------------------------------------------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error.|
**Example**
......@@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // The process of generating the symmetric key is omitted here.
let cipher; // The process of creating a Cipher instance is omitted here.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
if (err) {
console.error('Failed to init cipher');
return;
console.error(`Failed to init cipher, ${err.code}, ${err.message}`);
} else {
console.info(`Init cipher success`);
// Perform subsequent operations such as update.
}
console.log('Init cipher success');
// Perform subsequent operations such as update.
})
```
......@@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. <br>**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------ | ---------- | ---- | ---------------------- |
| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
| key | [Key](#key) | Yes | Key for encryption or decryption.|
| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. |
| Name | Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ------------------------------------------------------------ |
| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
| key | [Key](#key) | Yes | Key for encryption or decryption. |
| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.|
**Return value**
| Type | Description |
| ------------------- | --------------------------- |
| Promise\<void> | Promise used to return the result.|
| Type | Description |
| -------------- | -------------------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error.|
**Example**
......@@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // The process of generating the symmetric key is omitted here.
let cipher; // The process of creating a Cipher instance is omitted here.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => {
console.log('Init cipher success');
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null)
.then(() => {
console.info(`Init cipher success`);
// Perform subsequent operations such as update.
}, error => {
console.error(`Failed to init cipher, ${error.code}, ${error.message}`);
})
```
......@@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => {
update(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume.
Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. <br>This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2).
> **NOTE**
> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results. <br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output. <br>That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**. <br>When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted. <br>For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. <br>The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
> - RSA asymmetric encryption and decryption do not support **update()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------ |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. |
| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. |
| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error. |
**Example**
......@@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here.
let plainText = {data : stringToUint8Array('this is test!')};
cipher.update(plainText, (err, output) => { // Example of the encryption process.
if (err) {
console.error('Failed to update cipher');
return;
console.error(`Failed to update cipher`);
} else {
console.info(`Update cipher success`);
if (output != null) {
// Concatenate output.data to the ciphertext.
}
// Perform subsequent operations such as doFinal().
}
console.log('Update cipher success');
// Perform subsequent operations such as doFinal.
})
```
......@@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p
update(data : DataBlob) : Promise\<DataBlob>
Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume.
Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. <br>This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2).
> **NOTE**
> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results. <br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**. <br>When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted. <br>For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. <br>The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
> - RSA asymmetric encryption and decryption do not support **update()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.|
| Name| Type | Mandatory| Description |
| ---- | --------------------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.|
**Return value**
| Type | Description |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
| Type | Description |
| ------------------------------- | ------------------------------------------------ |
| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).|
**Error codes**
| ID| Error Message |
| -------- | -------------------------------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error. |
**Example**
......@@ -1575,9 +1793,15 @@ function stringToUint8Array(str) {
let cipher; // The process of creating a Cipher instance is omitted here.
// The init() process is omitted here.
let plainText = {data : stringToUint8Array('this is test!')};
cipher.update(data).then((output) => {
console.log('Update cipher success');
// Perform subsequent operations such as doFinal.
cipher.update(plainText)
.then((output) => {
console.info(`Update cipher success.`);
if (output != null) {
// Concatenate output.data to the ciphertext.
}
// Perform subsequent operations such as doFinal().
}, error => {
console.info(`Update cipher failed.`);
})
```
......@@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => {
doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result.
(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data. <br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. <br>The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
The output of **doFinal** varies depending on the symmetric encryption and decryption mode.
- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. <br>**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption.
- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption.
- For symmetric encryption and decryption in other modes, the output can be either of the following:
(1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result.
(2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value.
(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
> **NOTE**
> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization. <br>For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**.
> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------ |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.<br/>If data is already passed in by [update()](#update-4), **data** can be **null**. |
| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. |
| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| -------- | ----------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error. |
**Example**
......@@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i
// The init() and update() processes are omitted here.
cipher.doFinal(data, (err, output) => {
if (err) {
console.error('Failed to final cipher');
return;
console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`);
} else {
console.info(`Finalize cipher success`);
if (output != null) {
// Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
}
}
console.log('Final cipher success');
})
```
......@@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => {
doFinal(data : DataBlob) : Promise\<DataBlob>
Finalizes the data encryption or decryption operation. This API uses a promise to return the result.
The output of **doFinal** varies depending on the symmetric encryption and decryption mode.
- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption.
(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data. <br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. <br>The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
- For symmetric encryption and decryption in other modes, the output includes the following:
- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption.
- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
(1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results.
(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
(2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value.
> **NOTE**
> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization. <br>For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**.
> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. |
| Name| Type | Mandatory| Description |
| ---- | --------------------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.|
**Return value**
| Type | Description |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
| Type | Description |
| ------------------------------- | ------------------------------------------------ |
| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.|
**Error codes**
| ID| Error Message |
| -------- | -------------------------------------------- |
| 17620001 | memory error. |
| 17620002 | runtime error. |
| 17630001 | crypto operation error. |
**Example**
......@@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework';
let cipher; // The process of creating a Cipher instance is omitted here.
let data; // The process of preparing the data to encrypt or decrypt is omitted here.
// The init() and update() processes are omitted here.
cipher.doFinal(data).then((output) => {
console.log('Final cipher success');
cipher.doFinal(data)
.then(output => {
console.info(`Finalize cipher success`);
if (output != null) {
// Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
}
}, error => {
console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`);
})
```
**Callback example**:
**RSA encryption example (callback)**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
rsaGenerator.generateKeyPair(function (err, keyPair) {
let pubKey = keyPair.pubKey;
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
let input = {data : stringToUint8Array(plan) };
let plainText = "this is cipher text";
let input = {data : stringToUint8Array(plainText) };
cipher.doFinal(input, function (err, data) {
AlertDialog.show({ message : "EncryptOutPut is " + data.data} );
});
......@@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) {
});
```
**Promise example**:
**RSA encryption example (promise)**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
......@@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => {
let pubKey = rsaKeyPair.pubKey;
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode.
}).then(() => {
let input = { data : stringToUint8Array(plan) };
let plainText = "this is cipher text";
let input = { data : stringToUint8Array(plainText) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
```
> **NOTE**
> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data).
## cryptoFramework.createSign
......@@ -1717,9 +1987,9 @@ Creates a **Sign** instance.
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| Sign | **Sign** instance created.|
| Type| Description |
| ---- | -------------------------------- |
| Sign | **Sign** instance created.|
**Example**
......@@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256")
```
## Sign
Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**.
Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization.
The signing mode is determined in **createSign()**, and the key is set by **init()**.
If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**.
If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data.
If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| algName | string | Yes | No | Algorithm to use.|
### init
init(priKey : PriKey, callback : AsyncCallback\<void>) : void
Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result.
Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| priKey | Key |Yes| Private key used for the initialization.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------- |
| priKey | PriKey | Yes | Private key used for the initialization.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
init(priKey : PriKey) : Promise\<void>
Initializes a **Sign** instance using a private key. This API uses a promise to return the result.
Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| priKey | Key |Yes| Private key used for the initialization.|
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | ---------------- |
| priKey | PriKey | Yes | Private key used for the initialization.|
**Return value**
| Type | Description |
| ------------- | ----------- |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
### update
......@@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| data | DataBlob | Yes | Data to pass in.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
### update
......@@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
| data | DataBlob | Yes | Data to pass in.|
**Return value**
| Type | Description |
| ------------- | ----------- |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
### sign
......@@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| data | DataBlob | Yes | Data to pass in.|
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result. |
### sign
......@@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
| data | DataBlob | Yes | Data to pass in.|
**Return value**
| Type | Description |
| ------------- | ----------- |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
rsaGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, function (err, data) {
signer.update(input1, function (err, data) {
signer.sign(input2, function (err, data) {
SignMessageBlob = data;
console.info("sign output is " + SignMessageBlob.data);
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
let globalKeyPair;
let SignMessageBlob;
let plan1 = "This is Sign test plan1"; // The first segment of the data.
let plan2 = "This is Sign test plan2"; // The second segment of the data.
let input1 = { data : stringToUint8Array(plan1) };
let input2 = { data : stringToUint8Array(plan2) };
function signMessageCallback() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
rsaGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, function (err, data) {
signer.update(input1, function (err, data) { // Add the first segment of the data.
signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2.
SignMessageBlob = data;
AlertDialog.show({message : "res" + SignMessageBlob.data});
});
});
});
});
});
}
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
return signer.init(priKey);
}).then(() => {
return signer.update(input1);
}).then(() => {
return signer.sign(input2);
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
});
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
let globalKeyPair;
let SignMessageBlob;
let plan1 = "This is Sign test plan1"; // The first segment of the data.
let plan2 = "This is Sign test plan2"; // The second segment of the data.
let input1 = { data : stringToUint8Array(plan1) };
let input2 = { data : stringToUint8Array(plan2) };
function signMessagePromise() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
return signer.init(priKey);
}).then(() => {
return signer.update(input1); // Add the first segment of the data.
}).then(() => {
return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2.
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
AlertDialog.show({message : "output" + SignMessageBlob.data});
});
}
```
## cryptoFramework.createVerify
......@@ -1897,9 +2218,9 @@ Creates a **Verify** instance.
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| Verify | **Verify** instance created.|
| Type | Description |
| ------ | ---------------------------------- |
| Verify | **Verify** instance created.|
**Example**
......@@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256")
```
## Verify
Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**.
The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization.
The signature verification mode is determined in **createVerify()**, and key is set by **init()**.
If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**.
If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data.
If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| algName | string | Yes | No | Algorithm to be used for signature verification.|
### init
......@@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |Yes| Public key used for the initialization.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| pubKey | PubKey | Yes | Public key used for the initialization.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
### init
init(pubKey : PubKey) : Promise\<void>
Initializes the **Verify** instance using a public key. This API uses a promise to return the result.
......@@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |Yes|Public key used for the initialization.|
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | ---------------------------- |
| pubKey | PubKey | Yes | Public key used for the initialization.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
### update
......@@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| data | DataBlob | Yes | Data to pass in.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. |
### update
......@@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
| data | DataBlob | Yes | Data to pass in.|
**Return value**
| Type | Description |
| ------------- | ----------- |
| Type | Description |
| -------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
### verify
......@@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| signatureData | DataBlob | Yes | Signature data. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| Name | Type | Mandatory| Description |
| ------------- | -------------------- | ---- | ---------- |
| data | DataBlob | Yes | Data to pass in.|
| signatureData | DataBlob | Yes | Signature data. |
| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. |
### verify
......@@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in.|
| signatureData | DataBlob| Yes| Signature data.|
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | ---------- |
| data | DataBlob | Yes | Data to pass in.|
| signatureData | DataBlob | Yes | Signature data. |
**Return value**
| Type | Description |
| --------------- | ------------ |
| Type | Description |
| ----------------- | ---------------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let input1 = null;
let input2 = null;
let signMessageBlob = null; // Signed data, which is omitted here.
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
verifyer.verify(input2, signMessageBlob, function(err, data) {
console.info("verify result is " + data);
})
});
......@@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) {
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
let input1 = null;
let input2 = null;
let signMessageBlob = null; // Signed data, which is omitted here.
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
return verifyer.verify(input2, signMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
```
## cryptoFramework.createKeyAgreement
createKeyAgreement(algName : string) : KeyAgreement
......@@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance.
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. |
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------- |
| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.|
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| KeyAgreement | **KeyAgreement** instance created.|
| Type | Description |
| ------------ | ---------------------------------------- |
| KeyAgreement | **KeyAgreement** instance created.|
**Example**
......@@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
## KeyAgreement
Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**.
Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------------- |
| algName | string | Yes | No | Algorithm used for key agreement.|
### generateSecret
......@@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| priKey | PriKey |Yes| Private key used for key agreement.|
| pubKey | PubKey |Yes| Public key used for key agreement.|
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the shared secret generated. |
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ---------------------- |
| priKey | PriKey | Yes | Private key used for key agreement.|
| pubKey | PubKey | Yes | Public key used for key agreement.|
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the shared secret.|
### generateSecret
generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob>
Generates a shared secret. This API uses a promise to return the result.
......@@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| priKey | PriKey |Yes| Private key used for key agreement.|
| pubKey | PubKey |Yes| Public key used for key agreement.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------- |
| priKey | PriKey | Yes | Private key used for key agreement.|
| pubKey | PubKey | Yes | Public key used for key agreement.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Promise\<DataBlob> | Promise used to return the shared secret generated. |
| Type | Description |
| ------------------ | -------- |
| Promise\<DataBlob> | Promise used to return the shared secret.|
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) {
if (err) {
......@@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
keyAgreementPromise.then((secret) => {
......
......@@ -32,8 +32,8 @@ The table below describes the APIs used in this guide.
|AsyKeyGenerator|generateKeyPair() : Promise\<KeyPair>|Generates an asymmetric key pair randomly. This API uses a promise to return the result.|
|SymKeyGenerator|generateSymKey(callback : AsyncCallback\<SymKey>) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.|
|SymKeyGenerator|generateSymKey() : Promise\<SymKey>|Generates a symmetric key randomly. This API uses a promise to return the result.|
| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\<KeyPair>) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.<br>(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) |
| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair> | Converts the binary public key and private key data into a key pair. This API uses a promise to return the result.<br>(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) |
| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\<KeyPair>) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.<br>(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.)|
| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair> | Converts the binary data into a key pair. This API uses a promise to return the result.<br>(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.)|
| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\<SymKey>) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.|
| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair>| Converts binary data into a symmetric key. This API uses a promise to return the result.|
| Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)|
......@@ -264,14 +264,14 @@ function stringToUint8Array(str) {
return new Uint8Array(arr);
}
// Convert byte streams into strings in plaintext.
// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// Output the byte streams in hexadecimal format.
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
......@@ -383,14 +383,14 @@ function stringToUint8Array(str) {
return new Uint8Array(arr);
}
// Convert byte streams into strings in plaintext.
// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// Output the byte streams in hexadecimal format.
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
......@@ -500,7 +500,7 @@ Example 2: Encrypt and decrypt data using an asymmetric key pair.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode.
3. Perform encryption and decryption operations.
3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data.
......@@ -573,38 +573,24 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
|Sign|init(priKey : PriKey) : Promise\<void>|Sets a key and initializes the **Sign** instance. This API uses a promise to return the result.|
|Sign|update(data : DataBlob, callback : AsyncCallback\<void>) : void|Updates the data for signing. This API uses an asynchronous callback to return the result.|
|Sign|update(data : DataBlob) : Promise\<void>|Updates the data for signing. This API uses a promise to return the result.|
|Sign|sign(data : DataBlob, callback : AsyncCallback<DataBlob>) : void|Signs the data. This API uses an asynchronous callback to return the result.|
|Sign|sign(data : DataBlob) : Promise<DataBlob>|Signs the data. This API uses a promise to return the result.|
|Sign|sign(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void|Signs the data. This API uses an asynchronous callback to return the result.|
|Sign|sign(data : DataBlob) : Promise\<DataBlob>|Signs the data. This API uses a promise to return the result.|
|cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.|
|Verify|init(priKey : PriKey, callback : AsyncCallback\<void>) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.|
|Verify|init(priKey : PriKey) : Promise\<void>|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.|
|Verify|update(data : DataBlob, callback : AsyncCallback\<void>) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.|
|Verify|update(data : DataBlob) : Promise\<void>|Updates the data for signature verification. This API uses a promise to return the result.|
|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback<boolean>) : void|Verifies the signature. This API uses an asynchronous callback to return the result.|
|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise<boolean>|Verifies the signature. This API uses a promise to return the result.|
|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\<boolean>) : void|Verifies the signature. This API uses an asynchronous callback to return the result.|
|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\<boolean>|Verifies the signature. This API uses a promise to return the result.|
**How to Develop**
Example 1: Use RSA to sign data and verify the signature.
1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair.
2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature.
4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature.
1. Generate an RSA key pair.<br> Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair.
2. Create a **Sign** instance.<br> Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
3. Generate a signature.<br> Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature.
4. Create a **Verify** instance.<br> Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
5. Verify the signature.<br> Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
......@@ -684,25 +670,11 @@ function verifyMessageCallback() {
```
Example 2: Using ECC to sign data and verify the signature.
1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature.
4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature.
1. Generate an ECC key.<br> Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
2. Create a **Sign** instance.<br> Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
3. Generate a signature.<br> Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature.
4. Create a **Verify** instance.<br> Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
5. Verify the signature.<br> Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
......@@ -792,7 +764,7 @@ Typical message digest operations involve the following:
1. Create an **Md** instance.
2. Add one or more segments of data for generating a digest.
3. Compute a digest.
3. Compute a digest.
4. Obtain the algorithm and length of a digest.
**Available APIs**
......@@ -802,10 +774,10 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | -------------------------------------------------- |
| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. |
| Md | update(input : DataBlob, callback : AsyncCallback\<void\>) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.|
| Md | update(input : DataBlob) : Promise\<void\>; | Updates the data for a digest. This API uses a promise to return the result. |
| Md | digest(callback : AsyncCallback\<DataBlob\>) : void; | Generates the digest. This API uses an asynchronous callback to return the result. |
| Md | digest() : Promise\<DataBlob\>; | Generates the digest. This API uses a promise to return the result. |
| Md | update(input : DataBlob, callback : AsyncCallback\<void>) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.|
| Md | update(input : DataBlob) : Promise\<void>; | Updates the data for a digest. This API uses a promise to return the result. |
| Md | digest(callback : AsyncCallback\<DataBlob>) : void; | Generates the digest. This API uses an asynchronous callback to return the result. |
| Md | digest() : Promise\<DataBlob>; | Generates the digest. This API uses a promise to return the result. |
| Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. |
| Md | readonly algName : string; | Obtains the digest algorithm. |
......@@ -907,10 +879,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
**How to Develop**
1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
1. Generate an ECC key.<br> Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
2. Generate a shared secret by using the private and public ECC keys.
```javascript
......@@ -966,15 +935,15 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | --------------------------------------------------- |
| cryptoFramework | function createMac(algName : string) : Md; | Creates a **Mac** instance. |
| Mac | init(key : SymKey, callback : AsyncCallback\<void\>) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.|
| Mac | init(key : SymKey) : Promise\<void\>; | Initializes the MAC operation. This API uses a promise to return the result. |
| Mac | update(input : DataBlob, callback : AsyncCallback\<void\>) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. |
| Mac | update(input : DataBlob) : Promise\<void\>; | Updates the data for the MAC operation. This API uses a promise to return the result. |
| Mac | doFinal(callback : AsyncCallback\<DataBlob\>) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. |
| Mac | doFinal() : Promise\<DataBlob\>; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. |
| cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. |
| Mac | init(key : SymKey, callback : AsyncCallback\<void>) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.|
| Mac | init(key : SymKey) : Promise\<void>; | Initializes the MAC operation. This API uses a promise to return the result. |
| Mac | update(input : DataBlob, callback : AsyncCallback\<void>) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. |
| Mac | update(input : DataBlob) : Promise\<void>; | Updates the data for the MAC operation. This API uses a promise to return the result. |
| Mac | doFinal(callback : AsyncCallback\<DataBlob>) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. |
| Mac | doFinal() : Promise\<DataBlob>; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. |
| Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. |
| Mac | readonly algName : string; | Obtains the algorithm. |
| Mac | readonly algName : string; | Obtains the digest algorithm. |
**How to Develop**
......@@ -1089,8 +1058,8 @@ function doHmacByCallback(algName) {
Typical random number operations involve the following:
1. Generate a random number.
2. Set a seed based on the random number generated.
- Generate a random number.
- Set a seed based on the random number generated.
**Available APIs**
......@@ -1099,10 +1068,9 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | ---------------------------------------------- |
| cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. |
| Random | generateRandom(len : number, callback: AsyncCallback\<DataBlob\>) : void; | Generates a random number. This API uses an asynchronous callback to return the result. |
| Random | generateRandom(len : number) : Promise\<DataBlob\>; | Generates a random number. This API uses a promise to return the result. |
| Random | setSeed(seed : DataBlob, callback : AsyncCallback\<void\>) : void; | Sets a seed. This API uses an asynchronous callback to return the result.|
| Random | setSeed(seed : DataBlob) : Promise\<void\>; | Sets a seed. This API uses a promise to return the result. |
| Random | generateRandom(len : number, callback: AsyncCallback\<DataBlob>) : void; | Generates a random number. This API uses an asynchronous callback to return the result. |
| Random | generateRandom(len : number) : Promise\<DataBlob>; | Generates a random number. This API uses a promise to return the result. |
| Random | setSeed(seed : DataBlob) : void; | Sets a seed. |
**How to Develop**
......@@ -1124,10 +1092,11 @@ function doRandByPromise(len) {
var promiseGenerateRand = rand.generateRandom(len);
promiseGenerateRand.then(randData => {
console.error("[Promise]: rand result: " + randData.data);
var promiseSetSeed = rand.setSeed(randData);
return promiseSetSeed;
}).then(() => {
console.error("[Promise]: setSeed success");
try {
rand.setSeed(randData);
} catch (error) {
console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message);
}
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
......@@ -1146,13 +1115,11 @@ function doRandByCallback(len) {
console.error("[Callback]: err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
rand.setSeed(randData, (err1,) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: setSeed success");
}
});
try {
rand.setSeed(randData);
} catch (error) {
console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message);
}
}
});
}
......
# Crypto Framework Overview
The crypto framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly.
The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly.
## Working Principles
The crypto framework provides components in the following layers:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册