The **certificate** module provides APIs for performing certificate operations. The APIs of this module depend on the basic algorithm capabilities provided by the cryptography framework. For details about the cryptography framework APIs, see [Cryptography Framework](./js-apis-cryptoFramework.md).
> **NOTE**
>
> The initial APIs of this module are supported since API version 9.
| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicates the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data. |
| count | number | Yes | Yes | Number of certificates contained in the input data. |
| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
| callback | AsyncCallback\<void>) | No | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails. |
| date | string | Yes | Date of the certificate to check. |
| callback | AsyncCallback\<void> | No | Callback invoked to return the result. If **error** is **null**, the certificate is valid. If **error** is not **null**, the certificate has expired.|
**Example**
```js
importcryptoCertfrom'@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
letencodingData=null;
letencodingBlob={
data:encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO).
| callback | AsyncCallback\<boolean> | No | Callback invoked to return the result. The value **true** indicates that the certificate is revoked, and **false** indicates the opposite. |
**Example**
```js
importcryptoCertfrom'@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
letencodingData=null;
letencodingBlob={
data:encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
| Promise\<boolean> | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.|
**Example**
```js
importcryptoCertfrom'@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
letencodingData=null;
letencodingBlob={
data:encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
| callback | AsyncCallback\<void> | No | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails. |
Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result.
Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result.
The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](./../security/cert-overview.md#certificate-specifications).
| callback | AsyncCallback\<void> | No | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid. |
Validates the X.509 certificate chain. This API uses a promise to return the result.
The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](./../security/cert-overview.md#certificate-specifications).
console.error("[Promise]: error code: "+error.code+", message is: "+error.message);
}
```
## Mac
Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac).
console.error("[Promise]: error code: "+error.code+", message is: "+error.message);
}
```
## Md
Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd).
console.error("[Callback]: error code: "+error.code+", message is: "+error.message);
}
```
## 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).
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.
| 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. |
## 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).
| 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 |
## 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).
| 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.|
## 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).
| 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.|
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 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).
### clearMem
clearMem() : void
Clears the keys from the memory. This API returns the result synchronously.
console.info("key hex:"+uint8ArrayToShowStr(encodedKey.data));// Display all 0s.
```
## 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**.
| format | string | Yes | No | Format of the key.|
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
getEncoded() : DataBlob
Obtains the key in binary format. This API returns the result synchronously. The public key format must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format.
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**.
| format | string | Yes | No | Format of the key.|
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
getEncoded() : DataBlob
Obtains the key in binary format. This API returns the result synchronously. The private key format must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding mode.
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).
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 **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**.
- 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.
- 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.
## 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).
| 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**.|
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).
| 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. |
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.
letcipher;// The process of creating a Cipher instance is omitted here.
// The init() process is omitted here.
letplainText={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.log('Update cipher success');
// Perform subsequent operations such as doFinal.
})
```
### update
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.
Finalizes the data encryption or decryption operation. This API uses an asynchronous callback 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.
- 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.
| 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.|
letcipher;// The process of creating a Cipher instance is omitted here.
letdata;// The process of preparing the data to encrypt or decrypt is omitted here.
// The init() and update() processes are omitted here.
cipher.doFinal(data,(err,output)=>{
if(err){
console.error('Failed to final cipher');
return;
}
console.log('Final cipher success');
})
```
### doFinal
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.
- For symmetric encryption and decryption in other modes, the output includes the following:
(1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results.
(2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value.
| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.|
| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.|
Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**.
Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**.
Incorrect certificate signature information is found during the signature verification.
**Solution**
Check whether the certificate is correct.
## 19030003 Certificate Has Not Taken Effect
**Error Message**
The certificate has not taken effect.
**Possible Causes**
The certificate has not taken effect. The effective time of the certificate is later than the current system time or the time specified by the service.
**Solution**
1. Check whether the certificate is correct.
2. Check whether the system time is correct.
3. Compare the certificate effective time with the current system time to determine whether the certificate has taken effect.
## 19030004 Certificate Expired
**Error Message**
The certificate has expired.
**Possible Causes**
The certificate has expired. The certificate expiration time is earlier than the current system time or the time specified by the service.
**Solution**
1. Check whether the certificate is correct.
2. Check whether the system time is correct.
3. Compare the certificate expiration time time with the current system time to determine whether the certificate has expired.
## 19030005 Failed to Obtain the Certificate Issuer
**Error Message**
Failed to obtain the certificate issuer.
**Possible Causes**
The certificate issuer cannot be obtained during certificate verification.
**Solution**
Check whether the certificate is correct.
## 19030006 Key Cannot be Used for Signing a Certificate
**Error Message**
The key cannot be used for signing a certificate.
**Possible Causes**
The key cannot be used to sign certificates.
**Solution**
Check whether the certificate is correct.
## 19030007 Key Cannot be Used for Digital Signature
| cryptoCert | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback<X509Cert>) : void | Parses certificate data to create an **X509Cert** instance. This API uses an asynchronous callback to return the result.|
| cryptoCert | createX509Cert(inStream : EncodingBlob) : Promise<X509Cert> | Parses certificate data to create an **X509Cert** instance. This API uses a promise to return the result. |
| X509Cert | verify(key : cryptoFramework.PubKey, callback : AsyncCallback<void>) : void | Verifies the certificate signature. This API uses an asynchronous callback to return the result. |
| X509Cert | verify(key : cryptoFramework.PubKey) : Promise<void> | Verifies the certificate signature. This API uses a promise to return the result. |
| X509Cert | getEncoded(callback : AsyncCallback<EncodingBlob>) : void | Obtains serialized certificate data. This API uses an asynchronous callback to return the result. |
| X509Cert | getEncoded() : Promise<EncodingBlob> | Obtains serialized certificate data. This API uses a promise to return the result. |
| X509Cert | getPublicKey(callback : AsyncCallback<cryptoFramework.PubKey>) : void | Obtains the certificate public key. This API uses an asynchronous callback to return the result. |
| X509Cert | getPublicKey() : Promise<cryptoFramework.PubKey> | Obtains the certificate public key. This API uses a promise to return the result. |
| X509Cert | checkValidityWithDate(date: string, callback : AsyncCallback<void>) : void | Verifies the certificate validity period. This API uses an asynchronous callback to return the result. |
| X509Cert | checkValidityWithDate(date: string) : Promise<void> | Verifies the certificate validity period. This API uses a promise to return the result. |
| X509Cert | getVersion() : number | Obtains the certificate version. |
| X509Cert | getSerialNumber() : number | Obtains the certificate serial number. |
| cryptoCert | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback<X509Crl>) : void | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses an asynchronous callback to return the result.|
| cryptoCert | createX509Crl(inStream : EncodingBlob) : Promise<X509Crl> | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses a promise to return the result. |
| X509Crl | isRevoked(cert : X509Cert, callback : AsyncCallback<boolean>) : void | Checks whether the certificate is revoked. This API uses an asynchronous callback to return the result. |
| X509Crl | isRevoked(cert : X509Cert) : Promise<boolean> | Checks whether the certificate is revoked. This API uses a promise to return the result. |
| X509Crl | getEncoded(callback : AsyncCallback<EncodingBlob>) : void | Obtains the serialized CRL data. This API uses an asynchronous callback to return the result. |
| X509Crl | getEncoded() : Promise<EncodingBlob> | Obtains the serialized CRL data. This API uses a promise to return the result. |
| X509Crl | verify(key : cryptoFramework.PubKey, callback : AsyncCallback<void>) : void | Verifies the CRL signature. This API uses an asynchronous callback to return the result. |
| X509Crl | verify(key : cryptoFramework.PubKey) : Promise<void> | Verifies the CRL signature. This API uses a promise to return the result. |
| X509Crl | getVersion() : number | Obtains the CRL version. |
| X509Crl | getLastUpdate() : string | Obtains the date when the CRL was last updated. |
| X509Crl | getNextUpdate() : string | Obtains the next update date of the CRL. |
| X509Crl | getRevokedCert(serialNumber : number, callback : AsyncCallback<X509CrlEntry>) : void | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses an asynchronous callback to return the result. |
| X509Crl | getRevokedCert(serialNumber : number) : Promise<X509CrlEntry> | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses a promise to return the result. |
| X509Crl | getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback<X509CrlEntry>) : void | Obtains the specified X.509 certificate from the CRL. This API uses an asynchronous callback to return the result. |
| X509Crl | getRevokedCertWithCert(cert : X509Cert) : Promise<X509CrlEntry> | Obtains the specified X.509 certificate from the CRL. This API uses a promise to return the result. |
| X509Crl | getRevokedCerts(callback : AsyncCallback<Array<X509CrlEntry>>) : void | Obtains all revoked certificates in the CRL. This API uses an asynchronous callback to return the result. |
| X509Crl | getRevokedCerts() : Promise<Array<X509CrlEntry>> | Obtains all revoked certificates in the CRL. This API uses a promise to return the result. |
| X509Crl | getTbsInfo(callback : AsyncCallback<DataBlob>) : void | Obtains the tbsCertList of the CRL. This API uses an asynchronous callback to return the result. |
| X509Crl | getTbsInfo() : Promise<DataBlob> | Obtains the tbsCertList of the CRL. This API uses a promise to return the result. |
| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback<void>) : void | Verifies the certificate chain. This API uses an asynchronous callback to return the result. |
| CertChainValidator | validate(certChain : CertChainData) : Promise<void> | Verifies the certificate chain. This API uses a promise to return the result. |
// Certificate chain binary data: end-entity certificate data length + end-entity certificate data + CA certificate data length + CA certificate data (in L-V format).
| X509CrlEntry | getEncoded(callback : AsyncCallback<EncodingBlob>) : void; | Obtains the serialized data of the revoked certificate. This API uses an asynchronous callback to return the result.|
| X509CrlEntry | getEncoded() : Promise<EncodingBlob>; | Obtains the serialized data of the revoked certificate. This API uses a promise to return the result. |
| X509CrlEntry | getSerialNumber() : number; | Obtains the serial number of the revoked certificate. |
| X509CrlEntry | getCertIssuer(callback : AsyncCallback<DataBlob>) : void; | Obtains the issuer of the revoked certificate. This API uses an asynchronous callback to return the result. |
| X509CrlEntry | getCertIssuer() : Promise<DataBlob>; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. |
| X509CrlEntry | getRevocationDate(callback : AsyncCallback<string>) : void; | Obtains the revocation date of the certificate. This API uses an asynchronous callback to return the result. |
| X509CrlEntry | getRevocationDate() : Promise<string>; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. |
**How to Develop**
Example: Obtain a revoked certificate instance and call the APIs.
```javascript
importcryptoCertfrom'@ohos.security.cert';
// Example of a revoked certificate.
functioncrlEntrySample(){
// Create an **X509Crl** instance by using createX509Crl() of cryptoFramework.
letx509Crl=null;
// Obtain a revoked certificate instance. In this example, the instance is obtained by using getRevokedCert().
The **Certificate** module provides APIs for X.509 certificate operations. You can use the APIs to implement quick development.
## Basic Concepts
A digital certificate provides a method of digitally verifying the identity of a user, device, or service. X.509 is an international standard format public key certificates that securely associate cryptographic key pairs with identifies such as websites, individuals, or organizations. The crypto framework provides the following capabilities:
- X.509 certificate capabilities: parsing and serializing X.509 certificates, verifying X.509 certificate signatures, and querying certificate information.
- X.509 certificate revocation list (CRL) capabilities: parsing, serializing, and querying the X.509 CRL.
- Certificate chain validator capabilities: verifying the certificate chain (excluding the certificate validity period) and querying certificate chain algorithms.
## Constraints
- Multi-thread concurrent operations are not supported.
### Certificate Specifications
- Certificate chain verification
The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use **checkValidityWithDate()** of the **X509Cert** class.
- Certificate formats
Currently, only the certificates in DER and PEM formats are supported.
> This development guide applies to API version 9, OpenHarmony SDK version 3.2.7 or later, and JS development.
## Generating and Converting Keys
**When to Use**
Typical key generation operations involve the following:
1. Randomly create a key instance. This instance can be used for subsequent encryption and decryption.
2. Convert external or stored binary data into a key instance. This instance can be used for subsequent encryption and decryption.
3. Obtain the binary data of a key for storage or transmission.
> **NOTE**
>
> The key instance can be a symmetric key instance (**SymKey**) or an asymmetric key pair instance (**KeyPair**). The **KeyPair** instance consists a public key (PubKey) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
The table below describes the APIs used in this guide.
|Instance|API|Description|
|---|---|---|
|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|Creates an **AsyKeyGenerator** instance.|
|cryptoFramework|createSymKeyGenerator(algName : string) : SymKeyGenerator|Creates a **SymKeyGenerator** instance.|
|AsyKeyGenerator|generateKeyPair(callback : AsyncCallback\<KeyPair>) : void|Generates an asymmetric key pair randomly. This API uses an asynchronous callback to return the result.|
|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.) |
| 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**.)|
**How to Develop**
Example 1: Randomly generate an asymmetric key pair and obtain its binary data.
1. Create an **AsyKeyGenerator** instance.
2. Randomly generate an asymmetric key pair using **AsyKeyGenerator**.
3. Obtain binary data of the key pair generated.
For example, randomly generate an RSA key (1024 bits and two primes) using promise-based APIs.
Example 3: Generate an asymmetric key pair from the binary RSA key data.
1. Obtain the binary data of the RSA public or private key. The public key must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. The private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format.
2. Create an **AsyKeyGenerator** instance and call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance.
The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications.
Example 4: Generate an asymmetric key pair from the binary ECC key data.
1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance.
2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance.
Important data needs to be encrypted in data storage or transmission for security purposes. Typical encryption and decryption operations involve the following:
1. Encrypt and decrypt data using a symmetric key.
2. Encrypt and decrypt data using an asymmetric key pair.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
The table below describes the APIs used in this guide.
|Instance|API|Description|
|---|---|---|
|cryptoFramework|createCipher(transformation : string) : Cipher|Creates a **Cipher** instance.|
|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\<void>) : void|Sets a key and initializes the **Cipher** instance. This API uses an asynchronous callback to return the result.|
|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>|Sets a key and initializes the **Cipher** instance. This API uses a promise to return the result.|
|Cipher|update(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void|Updates the data for encryption and decryption. This API uses an asynchronous callback to return the result.|
|Cipher|update(data : DataBlob) : Promise\<DataBlob>|Updates the data for encryption and decryption. This API uses a promise to return the result.|
|Cipher|doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void|Finalizes the encryption or decryption. This API uses an asynchronous callback to return the result.|
|Cipher|doFinal(data : DataBlob) : Promise\<DataBlob>|Finalizes the encryption or decryption. This API uses a promise to return the result.|
**How to Develop**
Example 1: Encrypt and decrypt data using a symmetric key.
1. Create a **SymKeyGenerator** instance.
2. Use the key generator to generate a symmetric key.
3. Create a **Cipher** instance.
4. Encrypt or decrypt data.
For example, use AES GCM to encrypt and decrypt data using promise-based APIs.
- In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption.
- The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md).
- In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8.
## Signing Data and Verifying Signatures
**When to Use**
A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following:
1. Use RSA to sign data and verify the signature.
2. Use ECC to sign data and verify the signature.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
|Instance|API|Description|
|---|---|---|
|cryptoFramework|createSign(algName : string) : Sign|Creates a **Sign** instance.|
|Sign|init(priKey : PriKey, callback : AsyncCallback\<void>) : void|Sets a key and initializes the **Sign** instance. This API uses an asynchronous callback to return the result.|
|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.|
|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.|
**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.
A message digest is a fixed size numeric representation of the content of a message, computed by a has function. The message digest is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified.
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.
4. Obtain the algorithm and length of a digest.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
| 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 | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. |
Key agreement allows two parties to establish a shared secret over an insecure channel.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
|Instance|API|Description|
|---|---|---|
|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|Creates a **KeyAgreement** instance.|
|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\<DataBlob>) : void|Generates a shared secret. This API uses an asynchronous callback to return the result.|
|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob>|Generates a shared secret. This API uses a promise to return the result.|
**How to Develop**
1. Generate an ECC key.
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.
| 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. |
| Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. |
| Mac | readonly algName : string; | Obtains the algorithm. |
**How to Develop**
1. Call **createMac()** to create a **Mac** instance.
2. Call **init()** to initialize the **Mac** instance with the symmetric key passed in.
3. Call **update()** one or more times to add the data for computing a MAC.
| 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. |
**How to Develop**
1. Call **createRandom()** to create a **Random** instance.
2. Call **generateRandom()** to generate a random number of the given length.
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.
## Working Principles
The crypto framework provides components in the following layers:
- Framework layer: flexibly loads the plugins in the plugin layer to adapt to third-party algorithm libraries and shields the implement differences between the third-party algorithm libraries.
## Basic Concepts
### Symmetric Key
A symmetric key is a key used both to encrypt and decrypt data. In symmetric encryption, the sender converts information in plaintext into ciphertext using a key and certain algorithm for security purposes. The receiver converts the ciphertext into plaintext using the same key and algorithm.
- AES
Advanced Encryption Standard (AES) is the most common symmetric encryption algorithm. AES is a block cipher. A block cipher divides plaintext into fixed-length groups of bits, called blocks. A block is encrypted each time until the entire plaintext is encrypted. The block size in AES is 128 bits. That is, each block contains 16 bytes (8 bits/byte). The key length can be 128 bits, 192 bits, or 256 bits.
- 3DES
Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but its processing speed is lower. The AES is faster and more secure than 3DES.
### Asymmetric Key
In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For signing and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data.
- RSA key
The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows:
1. Generate two large prime numbers **p** and **q**.
2. Compute **n** = **p** x **q**.
**n** is used as the modulus for both the public and private keys, and is released as part of the public key.
3. Choose an integer **e** such that 1 < **e** < (**p** - 1) x (**q** - 1), that is, **e** and (**p** - 1) x (**q** - 1) are coprime.
4. Compute **d**.
**e** x **d** - 1 is a multiple of (**p** - 1) and (**q** - 1).
The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**.
In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see **Constraints**.
- ECC key
Elliptic-Curve Cryptography (ECC) is a public-key encryption based on the algebraic structure of elliptic curve over finite fields. The crypto framework provides a variety of ECC key generation capabilities.
### Encryption and Decryption
- Symmetric AES encryption and decryption
The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM.
AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows:
-**NoPadding**: no padding.
-**PKCS5**: pads a block cipher with a block size of 8 bytes.
-**PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes.
> **NOTE**
>
> In ECB and CBC modes, the plaintext length is not an integer multiple of 128 bits and must be padded.
- Symmetric 3DES encryption and decryption
3DES encryption and decryption apply the DES cipher three times to each data block obtain the ciphertext or plaintext.
The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB.
DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows:
-**NoPadding**: no padding.
-**PKCS5**: pads a block cipher with a block size of 8 bytes.
-**PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes.
> **NOTE**
>
> In ECB and CBC, the plaintext length is not an integer multiple of 64 bits and must be padded.
- Asymmetric RSA encryption and decryption
After the RSA public key (n, e) and private key (n, d) are held, the RSA encryption process is as follows:
Ciphertext = Plaintext ^ **e** mod **n**
The decryption process is as follows:
Plaintext = Ciphertext ^ **d** mod **n**
The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**.
RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows:
-**NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus.
-**PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus.
-**PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus.
**NOTE**
Length of the RSA key modulus = (Number of RSA bits + 7)/8
### Signing and Signature Verification
- RSA signing and signature verification
After the RSA public key (n, e) and private key (n, d) are held, the RSA signature is generated as follows:
Signature = Message ^ **d** mod **n**
The signature verification process is as follows:
Message = Signature ^ **d** mod **n**
The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest and then sign the message. The crypto framework provides the following padding modes for signing and signature verification:
-**PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. When this mode is used, the digest (**md**) must be set.
-**PSS**: The PSS mode is a padding algorithm based on the RSA algorithm. When it is used, the digest (**md**) and mask function (**mgf1_md**) are required.
- ECDSA
The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the unit bit strength of ECC is higher than that of other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms.
### Key Agreement
**ECDH**
Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library.
### Digest
The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. The message digest algorithm is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm.
When the same digest algorithm is used, the generated digest (hash value) has the following features:
- The same message always results in the same hash value.
- The digest generated is of the fixed length no matter the length of messages. (The digest length is determined by the algorithm used).
- It is almost impossible to find two different messages with the same hash value (the probability still exists, depending on the length of the digest).
There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section "**HMAC**".
MD algorithms include MD2, MD4, and MD5.
Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512.
### HMAC
Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify both the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed.
### Random Number
Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. Random numbers can be generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, repeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness.
- Internal state
A value in the random number generator memory. The same internal state produces the same sequence of the random number.
- Seed
A number used to initialize the internal state of a pseudorandom number generator. The random number generator generates a series of random sequences based on the seeds.
## Constraints
- The crypto framework does not support concurrent operations of multiple threads.
### Key Generation Specifications
**Symmetric Key Generation Specifications**
The following parameters are supported:
|Symmetric Key Algorithm|Key Length|String for Generating a Key|
|---|---|---|
|3DES|192|3DES192|
|AES|128|AES128|
|AES|192|AES192|
|AES|256|AES256|
**Asymmetric Key Generation Specifications**
-**RSA key generation**
The following parameters are supported:
|Asymmetric Key Algorithm|Key Length|Number of Primes|String for Generating a Key|
|---|---|---|---|
|RSA|512|2|RSA512\|PRIMES_2|
|RSA|768|2|RSA768\|PRIMES_2|
|RSA|1024|2|RSA1024\|PRIMES_2|
|RSA|1024|3|RSA1024\|PRIMES_3|
|RSA|2048|2|RSA2048\|PRIMES_2|
|RSA|2048|3|RSA2048\|PRIMES_3|
|RSA|3072|2|RSA3072\|PRIMES_2|
|RSA|3072|3|RSA3072\|PRIMES_3|
|RSA|4096|2|RSA4096\|PRIMES_2|
|RSA|4096|3|RSA4096\|PRIMES_3|
|RSA|4096|4|RSA4096\|PRIMES_4|
|RSA|8192|2|RSA8192\|PRIMES_2|
|RSA|8192|3|RSA8192\|PRIMES_3|
|RSA|8192|4|RSA8192\|PRIMES_4|
|RSA|8192|5|RSA8192\|PRIMES_5|
> **NOTE**
>
> When the RSA asymmetric key is generated, the default number of primes is 2 and the **PRIMES_2** parameter can be omitted.
-**ECC key generation**
The following parameters are supported:
|Asymmetric Key Algorithm|Key Length|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
### Encryption and Decryption Specifications
**Symmetric Encryption and Decryption**
The following symmetric encryption algorithms are supported: