提交 ac062802 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 cda81ba6
...@@ -125,6 +125,8 @@ ...@@ -125,6 +125,8 @@
- Security - Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.privacyManager](js-apis-privacyManager.md)
- [@ohos.security.cert](js-apis-cert.md)
- [@ohos.security.cryptoFramework]js-apis-cryptoFramework.md)
- [@ohos.security.huks ](js-apis-huks.md) - [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
......
# Certificate
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.
## Modules to Import
```javascript
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
```
## CertResult
Enumerates the error codes.
**System capability**: SystemCapability.Security.Cert
| Name | Default Value | Description |
| --------------------------------------| -------- | -----------------------------|
| INVALID_PARAMS | 401 | Invalid parameters. |
| NOT_SUPPORT | 801 | This operation is not supported. |
| ERR_OUT_OF_MEMORY | 19020001 | Memory error. |
| ERR_RUNTIME_ERROR | 19020002 | Runtime error. |
| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. |
| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. |
| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. |
| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. |
| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. |
| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. |
| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. |
## DataBlob
Defines a binary data array.
**System capability**: SystemCapability.Security.Cert
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | Yes | Yes | Data. |
## DataArray
Defines a list of data arrays.
**System capability**: SystemCapability.Security.Cert
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | Yes | Yes | Data list. |
## EncodingFormat
Enumerates the certificate encoding formats.
**System capability**: SystemCapability.Security.Cert
| Name | Default Value | Description |
| ------------| ---------| -----------|
| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format. |
| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format. |
## EncodingBlob
Defines a certificate binary array in encoding format.
### Attributes
**System capability**: SystemCapability.Security.Cert
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------------------------|
| data | Uint8Array | Yes | Yes | Certificate data. |
| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format.|
## CertChainData
Defines the certificate chain data, which is passed in as input parameters during certificate chain verification.
### Attributes
**System capability**: SystemCapability.Security.Cert
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| 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. |
| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format.|
## cryptoCert.createX509Cert
createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\<X509Cert>) : void
Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------ |
| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.|
| callback | AsyncCallback\<X509Cert> | No | Callback invoked to return the **X509Cert** instance created. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
}
});
```
## cryptoCert.createX509Cert
createX509Cert(inStream : EncodingBlob) : Promise\<X509Cert>
Creates an **X509Cert** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------ | ---- | ------------------ |
| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.|
**Return value**
| Type | Description |
| :------- | ---------------- |
| Promise\<X509Cert> |Promise used to return the **X509Cer** instance created.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
## X509Cert
Provides APIs for X.509 certificate operations.
### verify
verify(key : cryptoFramework.PubKey, callback : AsyncCallback\<void>) : void
Verifies the certificate signature. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------ |
| 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. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
// Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance.
let pubKey = null;
x509Cert.verify(pubKey, function (error, data) {
if (error != null) {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("verify success");
}
});
}
});
```
### verify
verify(key : cryptoFramework.PubKey) : Promise\<void>
Verifies the certificate signature. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
// Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance.
let pubKey = null;
x509Cert.verify(pubKey).then(result => {
Console.log("verify success");
}, error => {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | No | Callback invoked to return the serialized X.509 certificate data obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
x509Cert.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
Obtains the serialized X.509 certificate data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------------ | ---------------------- |
| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
x509Cert.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getPublicKey
getPublicKey(callback : AsyncCallback\<cryptoFramework.PubKey>) : void
Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback | No | Callback invoked to return the public key obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
x509Cert.getPublicKey(function (error, pubKey) {
if (error != null) {
Console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getPublicKey success");
}
});
}
});
```
### getPublicKey
getPublicKey() : Promise\<cryptoFramework.PubKey>
Obtains the public key of this X.509 certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ---------------- |
| cryptoFramework.PubKey | X.509 certificate public key obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
x509Cert.getPublicKey().then(pubKey => {
Console.log("getPublicKey success");
}, error => {
Console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### checkValidityWithDate
checkValidityWithDate(date: string, callback : AsyncCallback\<void>) : void
Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| 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
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let date = "150527000001Z";
x509Cert.checkValidityWithDate(date, function (error, data) {
if (error != null) {
Console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("checkValidityWithDate success");
}
});
}
});
```
### checkValidityWithDate
checkValidityWithDate(date: string) : Promise\<void>
Checks the validity period of this X.509 certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name| Type | Mandatory| Description|
| ------ | ------ | ---- | ---- |
| date | string | Yes | Date of the certificate to check.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
let date = "150527000001Z";
x509Cert.checkValidityWithDate(date).then(result => {
Console.log("checkValidityWithDate success");
}, error => {
Console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getVersion
getVersion() : number
Obtains the X.509 certificate version.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ---------------- |
| number | X.509 certificate version obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let version = x509Cert.getVersion();
}
});
```
### getSerialNumber
getSerialNumber() : number
Obtains the X.509 certificate serial number.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | X.509 certificate serial number obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let serialNumber = x509Cert.getSerialNumber();
}
});
```
### getIssuerName
getIssuerName() : DataBlob
Obtains the X.509 certificate issuer.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | ---------------------- |
| [DataBlob](#datablob) | X.509 certificate issuer obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let issuerName = x509Cert.getIssuerName();
}
});
```
### getSubjectName
getSubjectName() : DataBlob
Obtains the subject of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | -------------------- |
| [DataBlob](#datablob) | Subject name obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let subjectName = x509Cert.getSubjectName();
}
});
```
### getNotBeforeTime
getNotBeforeTime() : string
Obtains the start time of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------------- |
| string | Start time of the X.509 certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let notBefore = x509Cert.getNotBeforeTime();
}
});
```
### getNotAfterTime
getNotAfterTime() : string
Obtains the expiration time of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------------- |
| string | Expiration time of the X.509 certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let notAfter = x509Cert.getNotAfterTime();
}
});
```
### getSignature
getSignature() : DataBlob
Obtains the signature data of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | -------------------- |
| [DataBlob](#datablob) | Signature data obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let signature = x509Cert.getSignature();
}
});
```
### getSignatureAlgName
getSignatureAlgName() : string
Obtains the signing algorithm of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ------------------------ |
| string | X.509 certificate signing algorithm obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgName = x509Cert.getSignatureAlgName();
}
});
```
### getSignatureAlgOid
getSignatureAlgOid() : string
Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO).
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | --------------------------------- |
| string | OID obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgOid = x509Cert.getSignatureAlgOid();
}
});
```
### getSignatureAlgParams
getSignatureAlgParams() : DataBlob
Obtains the signing algorithm parameters of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | ------------------------ |
| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgParams = x509Cert.getSignatureAlgParams();
}
});
```
### getKeyUsage
getKeyUsage() : DataBlob
Obtains the key usage of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | -------------------- |
| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let keyUsage = x509Cert.getKeyUsage();
}
});
```
### getExtKeyUsage
getExtKeyUsage() : DataArray
Obtains the usage of the extended key of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| --------- | ------------------------ |
| [DataArray](#dataarray) | Usage of the extended key obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let extKeyUsage = x509Cert.getExtKeyUsage();
}
});
```
### getBasicConstraints
getBasicConstraints() : number
Obtains the basic constraints for obtaining this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | Basic constraints obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let basicConstraints = x509Cert.getBasicConstraints();
}
});
```
### getSubjectAltNames
getSubjectAltNames() : DataArray
Obtains the Subject Alternative Names (SANs) of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| --------- | ------------------------ |
| [DataArray](#dataarray) | SANs obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let subjectAltNames = x509Cert.getSubjectAltNames();
}
});
```
### getIssuerAltNames
getIssuerAltNames() : DataArray
Obtains the Issuer Alternative Names (IANs) of this X.509 certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| --------- | -------------------------- |
| [DataArray](#dataarray) | IANs obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Certificate binary data, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let issuerAltNames = x509Cert.getIssuerAltNames();
}
});
```
## cryptoCert.createX509Crl
createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\<X509Crl>) : void
Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------------------------- |
| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data.|
| callback | AsyncCallback\<X509Crl> | No | Callback invoked to return the **X509Crl** instance created. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
}
});
```
## cryptoCert.createX509Crl
createX509Crl(inStream : EncodingBlob) : Promise\<X509Crl>
Creates an **X509Crl** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------ | ---- | -------------------------- |
| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.|
**Return value**
| Type | Description |
| ------- | -------------------- |
| Promise\<X509Crl> | Promise used to return the **X509Crl** instance created.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
## X509Crl
Provides APIs for X.509 certificate CRL operations.
### isRevoked
isRevoked(cert : X509Cert, callback : AsyncCallback\<boolean>) : void
Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------------------- |
| cert | [X509Cert](#x509cert) | Yes | X.509 certificate to check.|
| 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
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// Create an X509Cert instance.
let x509Cert = null;
x509Crl.isRevoked(x509Cert, function (error, isRevoked) {
if (error != null) {
Console.log("call isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("call isRevoked success");
}
});
}
});
```
### isRevoked
isRevoked(cert : X509Cert) : Promise\<boolean>
Checks whether an X.509 certificate is revoked. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | -------------------- |
| cert | X509Cert | Yes | X.509 certificate to check.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// Create an X509Cert instance.
let x509Cert = null;
x509Crl.isRevoked(x509Cert).then(isRevoked => {
Console.log("call isRevoked success");
}, error => {
Console.log("call isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getType
getType() : string
Obtains the CRL type.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------- |
| string | CRL type obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let type = x509Crl.getType();
}
});
```
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<EncodingBlob> | No | Callback invoked to return the serialized X.509 CRL data obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
Obtains the serialized X.509 CRL data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------------ | -------------------------------- |
| Promise\<EncodingBlob> | Promise used to return the serialized X.509 CRL data obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### verify
verify(key : cryptoFramework.PubKey, callback : AsyncCallback\<void>) : void
Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ---------------------- |
| 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. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// Generate the public key by AsyKeyGenerator.
let pubKey = null;
x509Crl.verify(pubKey, function (error, data) {
if (error != null) {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("verify success");
}
});
}
});
```
### verify
verify(key : cryptoFramework.PubKey) : Promise\<void>
Verifies the signature of the X.509 CRL. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------- |
| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from "@ohos.security.cryptoFramework"
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// Generate the public key by AsyKeyGenerator.
let pubKey = null;
x509Crl.verify(pubKey).then(result => {
Console.log("verify success");
}, error => {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getVersion
getVersion() : number
Obtains the version of the X.509 CRL.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------------------- |
| number | Version of the X.509 CRL obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let version = x509Crl.getVersion();
}
});
```
### getIssuerName
getIssuerName() : DataBlob
Obtains the issuer of the X.509 CRL.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | ------------------------------ |
| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let issuerName = x509Crl.getIssuerName();
}
});
```
### getLastUpdate
getLastUpdate() : string
Obtains the date when the X.509 CRL was last updated.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ------------------------------------ |
| string | Last update date of the X.509 CRL.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let lastUpdate = x509Crl.getLastUpdate();
}
});
```
### getNextUpdate
getNextUpdate() : string
Obtains the date when the CRL will be updated the next time.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ------------------------------------ |
| string | Next update date obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let nextUpdate = x509Crl.getNextUpdate();
}
});
```
### getRevokedCert
getRevokedCert(serialNumber : number, callback : AsyncCallback\<X509CrlEntry>) : void
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.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------- | ---- | -------------- |
| serialNumber | number | Yes | Serial number of the certificate.|
| callback | AsyncCallback\<X509CrlEntry> | No | Callback invoked to return the revoked X.509 certificate. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// Set the serial number of the corresponding certificate.
let serialNumber = 1000;
x509Crl.getRevokedCert(serialNumber, function (error, entry) {
if (error != null) {
Console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCert success");
}
});
}
});
```
### getRevokedCert
getRevokedCert(serialNumber : number) : Promise\<X509CrlEntry>
Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | ---- | -------------- |
| serialNumber | number | Yes | Serial number of the certificate.|
**Return value**
| Type | Description |
| ------------ | ---------------------- |
| Promise\<X509CrlEntry> | Promise used to return the revoked X.509 certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// Set the serial number of the corresponding certificate.
let serialNumber = 1000;
x509Crl.getRevokedCert(serialNumber).then(entry => {
Console.log("getRevokedCert success");
}, error => {
Console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevokedCertWithCert
getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback\<X509CrlEntry>) : void
Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------ |
| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.|
| callback | AsyncCallback\<X509CrlEntry> | No | Callback invoked to return the revoked X.509 certificate obtained. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// Create an X509Cert instance.
let x509Cert = null;
x509Crl.getRevokedCertWithCert(x509Cert, function (error, entry) {
if (error != null) {
Console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCertWithCert success");
}
});
}
});
```
### getRevokedCertWithCert
getRevokedCertWithCert(cert : X509Cert) : Promise\<X509CrlEntry>
Obtains the revoked X.509 certificate based on the specified certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ------------ |
| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.|
**Return value**
| Type | Description |
| ------------ | ---------------------- |
| Promise\<X509CrlEntry> | Promise used to return the revoked X.509 certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// Create an X509Cert instance.
let x509Cert = null;
x509Crl.getRevokedCertWithCert(x509Cert).then(entry => {
Console.log("getRevokedCertWithCert success");
}, error => {
Console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevokedCerts
getRevokedCerts(callback : AsyncCallback<Array\<X509CrlEntry>>) : void
Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback<Array\<X509CrlEntry>> | No | Callback invoked to return the revoked X.509 certificates obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getRevokedCerts(function (error, array) {
if (error != null) {
Console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCerts success");
}
});
}
});
```
### getRevokedCerts
getRevokedCerts() : Promise<Array\<X509CrlEntry>>
Obtains all the revoked X.509 certificates. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------------------- | ---------------------- |
|Promise<Array\<X509CrlEntry>> | Promise used to return a list of revoked X.509 certificates.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getRevokedCerts().then(array => {
Console.log("getRevokedCerts success");
}, error => {
Console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getTbsInfo
getTbsInfo(callback : AsyncCallback\<DataBlob>) : void
Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<[DataBlob](#datablob)> | No | Callback invoked to return the tbsCertList information obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getTbsInfo(function (error, tbsInfo) {
if (error != null) {
Console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getTbsInfo success");
}
});
}
});
```
### getTbsInfo
getTbsInfo() : Promise\<DataBlob>
Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | --------------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the **tbsCertList** information obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getTbsInfo().then(tbsInfo => {
Console.log("getTbsInfo success");
}, error => {
Console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getSignature
getSignature() : DataBlob
Obtains the signature data of the X.509 CRL.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | ------------------------------ |
| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let signature = x509Crl.getSignature();
}
});
```
### getSignatureAlgName
getSignatureAlgName() : string
Obtains the signing algorithm of the X.509 CRL.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------------------- |
| string | Signing algorithm obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgName = x509Crl.getSignatureAlgName();
}
});
```
### getSignatureAlgOid
getSignatureAlgOid() : string
Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO).
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | --------------------------------------------- |
| string | OID of the X.509 CRL signing algorithm obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgOid = x509Crl.getSignatureAlgOid();
}
});
```
### getSignatureAlgParams
getSignatureAlgParams() : DataBlob
Obtains the parameters of the X.509 CRL signing algorithm.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | ---------------------------------- |
| [DataBlob](#datablob) | Algorithm parameters obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Binary data of the CRL, which must be set based on the service.
let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgParams = x509Crl.getSignatureAlgParams();
}
});
```
## cryptoCert.createCertChainValidator
createCertChainValidator(algorithm :string) : CertChainValidator
Creates a **CertChainValidator** object.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------------------------------------ |
| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.|
**Return value**
| Type | Description |
| ------------------ | -------------------- |
| CertChainValidator | **CertChainValidator** object created.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
let validator = cryptoCert.createCertChainValidator("PKIX");
```
## CertChainValidator
Provides APIs for certificate chain validator operations.
### validate
validate(certChain : CertChainData, callback : AsyncCallback\<void>) : void
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).
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------- | ---- | ------------------------ |
| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.|
| 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. |
**Example**
```js
import cryptoCert from '@ohos.security.cert';
let validator = cryptoCert.createCertChainValidator("PKIX");
// Certificate chain binary data, which must be set based on the service.
let encodingData = null;
// Number of certificates in the certificate chain. It must be set based on the service.
let certCount = 2;
let certChainData = {
data: encodingData,
count: certCount,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
validator.validate(certChainData, function (error, data) {
if (error != null) {
Console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("validate success");
}
});
```
### validate
validate(certChain : CertChainData) : Promise\<void>
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).
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------- | ---- | ------------------------ |
| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
let validator = cryptoCert.createCertChainValidator("PKIX");
// Certificate chain binary data, which must be set based on the service.
let encodingData = null;
// Number of certificates in the certificate chain. It must be set based on the service.
let certCount = 2;
let certChainData = {
data: encodingData,
count: certCount,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
validator.validate(certChainData).then(result => {
Console.log("validate success");
}, error => {
Console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### algorithm
algorithm : string
Obtains the algorithm of the X.509 certificate chain validator.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ------------------------ |
| string | Algorithm of the X.509 certificate chain validator obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
let validator = cryptoCert.createCertChainValidator("PKIX");
let algorithm = validator.algorithm;
```
## X509CrlEntry
Provides APIs for operating the revoked certificates.
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | No | Callback invoked to return the serialized data of the revoked certificate.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
Obtains the serialized data of this revoked certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------------ | -------------------------- |
| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getSerialNumber
getSerialNumber() : number
Obtains the serial number of this revoked certificate.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | ---------------------- |
| number | Serial number of the revoked certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
let serialNumber = x509CrlEntry.getSerialNumber();
```
### getCertIssuer
getCertIssuer(callback : AsyncCallback\<DataBlob>) : void
Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<[DataBlob](#datablob)> | No | Callback invoked to return the issuer of the revoked certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getCertIssuer(function (error, issuer) {
if (error != null) {
Console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getCertIssuer success");
}
});
```
### getCertIssuer
getCertIssuer() : Promise\<DataBlob>
Obtains the issuer of this revoked certificate. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| -------- | -------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the issuer of the revoked certificate obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getCertIssuer().then(issuer => {
Console.log("getCertIssuer success");
}, error => {
Console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevocationDate
getRevocationDate(callback : AsyncCallback\<string>) : void
Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Cert
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<string> | No | Callback invoked to return the certificate revocation date obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getRevocationDate(function (error, date) {
if (error != null) {
Console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevocationDate success");
}
});
```
### getRevocationDate
getRevocationDate() : Promise\<string>
Obtains the date when the certificate was revoked. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Cert
**Return value**
| Type | Description |
| ------ | -------------------- |
| Promise\<string> | Promise used to return the certificate revocation date obtained.|
**Example**
```js
import cryptoCert from '@ohos.security.cert';
// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
let x509CrlEntry = null;
x509CrlEntry.getRevocationDate().then(date => {
Console.log("getRevocationDate success");
}, error => {
Console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
# Crypto Framework
The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9.
## Modules to Import
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
```
## Result
Enumerates the error codes.
**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. |
## DataBlob
Defines a binary data array.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | Yes | Yes | Data. |
## cryptoFramework.createMac
createMac(algName : string) : Mac
Creates a **Mac** instance for message authentication code (MAC) operations.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | Yes | Digest algorithm to use, which can be SHA-1, SHA-224, SHA-256, SHA-384, or SHA-512.|
**Return value**
| Type| Description |
| ---- | --------------------------------------- |
| Mac | [Mac](#mac) instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
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).
### **Attributes**
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | -------------------- |
| algName | string | Yes | No | Digest algorithm to use.|
### init
init(key : SymKey, callback : AsyncCallback\<void>) : void;
Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| key | SymKey | Yes | Shared symmetric key. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
});
});
```
### init
init(key : SymKey) : Promise\<void>;
Initializes the MAC computation using a symmetric key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| key | SymKey | Yes | Shared symmetric key.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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);
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### update
update(input : DataBlob, callback : AsyncCallback\<void>) : void;
Updates the MAC computation 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.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var KeyBlob;
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");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
let blob;
mac.update(blob, (err2, data) => {
if (err2) {
console.error("[Callback] err: " + err2.code);
}
});
});
});
```
### update
update(input : DataBlob) : Promise\<void>;
Updates the MAC computation 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.|
**Return value**
| Type | Description |
| --------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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 => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### doFinal
doFinal(callback : AsyncCallback\<DataBlob>) : void;
Finalizes the MAC computation. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var KeyBlob;
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");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
let blob;
mac.update(blob, (err2, ) => {
if (err2) {
console.error("[Callback] err: " + err2.code);
}
mac.doFinal((err3, macOutput) => {
if (err3) {
console.error("[Callback] err: " + err3.code);
} else {
console.error("[Promise]: HMAC result: " + macOutput);
}
});
});
});
});
```
### doFinal
doFinal() : Promise\<DataBlob>
Finalizes the MAC computation. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
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 => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### getMacLength
getMacLength() : number
Obtains the MAC length, in bytes.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| ------ | ------------------------- |
| number | MAC length obtained.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
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 => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
AlertDialog.show({message: "MAC len: " + macLen});
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## cryptoFramework.createMd
createMd(algName : string) : Md
Creates an **Md** instance for message digest operations.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | Yes | Digest algorithm to use, which can be SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, or MD5.|
**Return value**
| Type| Description |
| ---- | ------------------------------------- |
| Md | [Md](#md) instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
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).
### **Attributes**
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | -------------------- |
| algName | string | Yes | No | Digest algorithm to use.|
### 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.
**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.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
md.update(blob, (err,) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
});
```
### update
update(input : DataBlob) : Promise\<void>;
Updates the message digest data with the message passed in. 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.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
// do something
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### digest
digest(callback : AsyncCallback\<DataBlob>) : void
Generates a message digest. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------- |
| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
md.update(blob, (err,) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
md.digest((err1, mdOutput) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: MD result: " + mdOutput);
}
});
});
```
### digest
digest() : Promise\<DataBlob>
Generates a message digest. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### getMdLength
getMdLength() : number
Obtains the message digest length, in bytes.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| ------ | ------------------------ |
| number | Message digest length obtained. |
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
AlertDialog.show({message: "MD len: " + mdLen});
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## cryptoFramework.createRandom
createRandom() : Random
Creates a **Random** instance for generating random numbers and setting seeds.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| ------ | --------------------------------------------- |
| Random | [Random](#random) instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
try {
var rand = cryptoFramework.createRandom();
} catch (error) {
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).
### generateRandom
generateRandom(len : number, callback: AsyncCallback\<DataBlob>) : void;
Generates a random number of the given length. This API uses an asynchronous callback to return the result.
**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.|
**Example**
```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);
}
rand.generateRandom(12, (err, randData) => {
if (err) {
console.error("[Callback] err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
}
});
```
### generateRandom
generateRandom(len : number) : Promise\<DataBlob>;
Generates a random number of the given length. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| len | number | Yes | Length of the random number to generate.|
**Return value**
| Type | Description |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise used to return the result.|
**Example**
```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);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### setSeed
setSeed(seed : DataBlob, callback : AsyncCallback\<void>) : 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.|
**Example**
```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);
}
rand.generateRandom(12, (err, randData) => {
if (err) {
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");
}
});
}
});
```
### 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.
**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. |
## 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).
**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 |
## 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).
**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.|
## 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).
**System capability**: SystemCapability.Security.CryptoFramework
| 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.|
## CryptoMode
Enumerates the cryptographic operations.
**System capability**: SystemCapability.Security.CryptoFramework
| 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.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| 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 hexadecimal format. This API returns the result synchronously.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| 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 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).
### clearMem
clearMem() : void
Clears the keys from the memory. This API returns the result synchronously.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
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 encodedKey = key.getEncoded();
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.
```
## 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**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| 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.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type |Description |
| ------- | ----------- |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
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**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ---------------------- |
| 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.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type |Description |
| ------- | ----------- |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
```
### clearMem
clearMem() : void
Clears the keys from the memory. This API returns the result synchronously.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
key.clearMem();
```
## 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).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ----------------------------- |
| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------- |
| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.|
**Example**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
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).
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| 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.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------- | ---- | ------------------- |
| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.|
**Example**
```js
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);
})
```
### generateSymKey
generateSymKey() : Promise\<SymKey>
Generates a key randomly. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
**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);
})
```
### convertKey
convertKey(key : DataBlob, callback : AsyncCallback\<SymKey>) : void
Converts a key. This API uses an asynchronous callback to return the result.
**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.|
**Example**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
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);
})
```
### convertKey
convertKey(key : DataBlob) : Promise\<SymKey>
Converts a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| key | [DataBlob](#datablob) | Yes | Key to convert.|
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
**Example**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
symKeyGenerator.convertKey(keyMaterial).then((symKey) => {
console.log('Convert symKey success, algName:' + symKey.algName);
})
```
## cryptoFramework.createAsyKeyGenerator
createAsyKeyGenerator(algName : string) : AsyKeyGenerator
Creates an **AsyKeyGenerator** instance based on the specified algorithm.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | -------------------------------- |
| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
**Return value**
| Type | Description |
| --------------- | -------------------------- |
| asyKeyGenerator | **AsyKeyGenerator** instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
```
## AsyKeyGenerator
Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| 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 |
| -------- | -------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<KeyPair> | Yes | Callback invoked to return the key pair obtained.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.generateKeyPair((err, keyPair) => {
if (err) {
console.error("generateKeyPair: error.");
return;
}
console.info("generateKeyPair: success.");
})
```
### 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 |
| --------------------- | ------------------------------- |
| Promise\<KeyPair> | Promise used to return the key pair generated.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let keyGenPromise = asyKeyGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
console.info("generateKeyPair success.");
}).catch(error => {
console.error("generateKeyPair error.");
});
```
### 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**.
**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. |
| callback | AsyncCallback\<KeyPair> | Yes | Callback invoked to return the key pair obtained.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
if (err) {
console.error("convertKey: error.");
return;
}
console.info("convertKey: success.");
})
```
### 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**.
**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. |
**Return value**
| Type | Description |
| --------------------- | ------------------------------- |
| Promise\<KeyPair> | Promise used to return the key pair generated.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey);
keyGenPromise.then( keyPair => {
console.info("convertKey success.");
}).catch(error => {
console.error("convertKey error.");
});
```
**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.
- 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).
**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**.|
**Return value**
| Type | Description |
| ------ | ------------------------ |
| [Cipher](#cipher) | [Cipher](#cipher) instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let cipherAlgoName = '3DES192|ECB|PKCS7';
var cipher;
try {
cipher = cryptoFramework.createCipher(cipherAlgoName);
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).
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable | Writable | Description |
| ------- | ------ | -------- | ----------- | ---------------------------- |
| algName | string | Yes | No | Algorithm to use.|
### 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.
**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.|
**Example**
```js
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.log('Init cipher success');
// Perform subsequent operations such as update.
})
```
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**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. |
**Return value**
| Type | Description |
| ------------------- | --------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
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');
// Perform subsequent operations such as update.
})
```
### update
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.
**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.|
**Example**
```js
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 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(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.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.|
**Return value**
| Type | Description |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
**Example**
```js
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 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.
})
```
### doFinal
doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
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.
**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.|
**Example**
```js
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, (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.
**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**. |
**Return value**
| Type | Description |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
**Example**
```js
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');
})
```
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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) };
cipher.doFinal(input, function (err, data) {
AlertDialog.show({ message : "EncryptOutPut is " + data.data} );
});
});
});
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
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) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
```
## cryptoFramework.createSign
createSign(algName : string) : Sign
Creates a **Sign** instance.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| 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.|
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| Sign | **Sign** instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|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()**.
### 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.
**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.|
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
Initializes a **Sign** instance using a private key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| priKey | Key |Yes| Private key used for the initialization.|
**Return value**
| Type | Description |
| ------------- | ----------- |
| Promise\<void> | Promise used to return the result.|
### update
update(data : DataBlob, callback : AsyncCallback\<void>) : void
Updates the data to be signed. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
### update
update(data : DataBlob) : Promise\<void>;
Updates the data to be signed. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
**Return value**
| Type | Description |
| ------------- | ----------- |
| Promise\<void> | Promise used 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.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
### sign
sign(data : DataBlob) : Promise\<DataBlob>
Signs the data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
**Return value**
| 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);
});
});
});
});
```
**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);
});
```
## cryptoFramework.createVerify
createVerify(algName : string) : Verify
Creates a **Verify** instance.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| 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.|
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| Verify | **Verify** instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|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()**.
### init
init(pubKey : PubKey, callback : AsyncCallback\<void>) : void
Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |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.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |Yes|Public key used for the initialization.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Promise\<void> | Promise used to return the result.|
### update
update(data : DataBlob, callback : AsyncCallback\<void>) : void
Updates the data for signature verification. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | Yes | Message to pass in. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
### update
update(data : DataBlob) : Promise\<void>;
Updates the data for signature verification. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in. |
**Return value**
| Type | Description |
| ------------- | ----------- |
| Promise\<void> | Promise used 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.
**System capability**: SystemCapability.Security.CryptoFramework
**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.|
### verify
verify(data : DataBlob, signatureData : DataBlob) : Promise\<boolean>
Verifies the signature. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | Yes | Message to pass in.|
| signatureData | DataBlob| Yes| Signature data.|
**Return value**
| Type | Description |
| --------------- | ------------ |
| Promise\<boolean> | Promise used to return the result.|
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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) {
console.info("verify result is " + data);
})
});
})
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
```
## cryptoFramework.createKeyAgreement
createKeyAgreement(algName : string) : KeyAgreement
Creates a **KeyAgreement** instance.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. |
**Return value**
| Type| Description |
| ---- | ------------------------------ |
| KeyAgreement | **KeyAgreement** instance created.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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()**.
### generateSecret
generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\<DataBlob>) : void
Generates a shared secret. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**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. |
### generateSecret
generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob>
Generates a shared secret. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
| 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. |
**Callback example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) {
if (err) {
console.error("keyAgreement error.");
return;
}
console.info("keyAgreement output is " + secret.data);
});
```
**Promise example**:
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
keyAgreementPromise.then((secret) => {
console.info("keyAgreement output is " + secret.data);
}).catch((error) => {
console.error("keyAgreement error.");
});
```
# Certificate Error Codes
## 19020001 Memory Error
**Error Message**
Memory error.
**Possible Causes**
The memory allocation failed.
**Solution**
1. Check whether the system is running properly.
2. Check whether the service data is too long.
## 19020002 Runtime Error
**Error Message**
Runtime error.
**Possible Causes**
An unexpected error occurs.
**Solution**
Check whether the system is running properly.
## 19030001 Crypto Operation Error
**Error Message**
Crypto operation error.
**Possible Causes**
An error occurs when the cryptography framework interacts with a third-party algorithm library.
**Solution**
1. Check whether the input parameters are correct.
2. Check whether the third-party algorithm library functions properly.
## 19030002 Certificate Signature Verification Failed
**Error Message**
The certificate signature verification failed.
**Possible Causes**
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
**Error Message**
The key cannot be used for digital signature.
**Possible Causes**
The key cannot be used for digital signature.
**Solution**
Check whether the certificate is correct.
# Crypto Framework Error Codes
## 17620001 Memory Error
**Error Message**
Memory error.
**Possible Causes**
The memory allocation failed.
**Solution**
1. Check whether the system is running properly.
2. Check whether the service data is too long.
## 17620002 Runtime Error
**Error Message**
Runtime error.
**Possible Causes**
An unexpected error occurs.
**Solution**
Check whether the system is running properly.
## 19030001 Crypto Operation Error
**Error Message**
Crypto operation error.
**Possible Causes**
An error occurs when the cryptography framework interacts with a third-party algorithm library.
**Solution**
1. Check whether the input parameters are correct.
2. Check whether the third-party algorithm library functions properly.
...@@ -11,6 +11,12 @@ ...@@ -11,6 +11,12 @@
- Key Management - Key Management
- [HUKS Overview](huks-overview.md) - [HUKS Overview](huks-overview.md)
- [HUKS Development](huks-guidelines.md) - [HUKS Development](huks-guidelines.md)
- Crypto Framework
- [Crypto Framework Overview](cryptoFramework-overview.md)
- [Crypto Framework Development](cryptoFramework-guidelines.md)
- Certificate
- [Certificate Overview](cert-overview.md)
- [Certificate Development](cert-guidelines.md)
- hapsigner - hapsigner
- [hapsigner Overview](hapsigntool-overview.md) - [hapsigner Overview](hapsigntool-overview.md)
- [hapsigner Guide](hapsigntool-guidelines.md) - [hapsigner Guide](hapsigntool-guidelines.md)
# Certificate Development
> **NOTE**
>
> This development guide applies to API version 9, OpenHarmony SDK version 3.2.9 or later, and JS development.
## Using Certificates
**When to Use**
Typical operations involve the following:
1. Parse X.509 certificate data to generate a certificate object.
2. Obtain certificate information, such as the version and serial number of the certificate.
3. Obtains the serialized data of the certificate object.
4. Obtain the certificate public key.
5. Verify the certificate signature.
6. Verify the certificate validity period.
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | -------------------------------------------- |
| 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. |
| X509Cert | getIssuerName() : DataBlob | Obtains the certificate issuer. |
| X509Cert | getSubjectName() : DataBlob | Obtains the certificate subject. |
| X509Cert | getNotBeforeTime() : string | Obtains the time from which the certificate takes effect. |
| X509Cert | getNotAfterTime() : string | Obtains the expiration time of the certificate. |
| X509Cert | getSignature() : DataBlob | Obtains the certificate signature. |
| X509Cert | getSignatureAlgName() : string | Obtain the certificate signing algorithm. |
| X509Cert | getSignatureAlgOid() : string | Obtains the certificate signing algorithm object identifier (OID). |
| X509Cert | getSignatureAlgParams() : DataBlob | Obtains the certificate signing algorithm parameters. |
| X509Cert | getKeyUsage() : DataBlob | Obtains the key usage of the certificate. |
| X509Cert | getExtKeyUsage() : DataArray | Obtains the usage of the certificate extension key. |
| X509Cert | getBasicConstraints() : number | Obtains the basic constraints on the certificate. |
| X509Cert | getSubjectAltNames() : DataArray | Obtains the Subject Alternative Names (SANs) of the certificate. |
| X509Cert | getIssuerAltNames() : DataArray | Obtains the Issuer Alternative Names (IANs) of the certificate. |
**How to Develop**
Example: Parse the X.509 certificate data to create an **X509Cert** instance and call APIs to perform certificate operations.
```javascript
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from '@ohos.security.cryptoFramework';
// Certificate data, which is only an example. The certificate data varies with the service.
let certData = "-----BEGIN CERTIFICATE-----\n"
+ "IBzTCCAXCgAwIBAgIGAXKnMKNyMAwGCCqBHM9VAYN1BQAwSTELMAkGA1UEBhMC\n"
+ "04xDjAMBgNVBAoTBUdNU1NMMRAwDgYDVQQLEwdQS0kvU00yMRgwFgYDVQQDEw9S\n"
+ "290Q0EgZm9yIFRlc3QwIhgPMjAxNTEyMzExNjAwMDBaGA8yMDM1MTIzMDE2MDAw\n"
+ "FowSTELMAkGA1UEBhMCQ04xDjAMBgNVBAoTBUdNU1NMMRAwDgYDVQQLEwdQS0kv\n"
+ "00yMRgwFgYDVQQDEw9Sb290Q0EgZm9yIFRlc3QwWTATBgcqhkjOPQIBBggqgRzP\n"
+ "QGCLQNCAATj+apYlL+ddWXZ7+mFZXZJGbcJFXUN+Fszz6humeyWZP4qEEr2N0+a\n"
+ "dwo/21ft232yo0jPLzdscKB261zSQXSoz4wPDAZBgNVHQ4EEgQQnGnsD7oaOcWv\n"
+ "CTrspwSBDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIAxjAMBggqgRzP\n"
+ "QGDdQUAA0kAMEYCIQCEnW5BlQh0vmsOLxSoXYc/7zs++wWyFc1tnBHENR4ElwIh\n"
+ "I1Lwu6in1ruflZhzseWulXwcITf3bm/Y5X1g1XFWQUH\n"
+ "-----END CERTIFICATE-----\n";
// Convert the string into a Uint8Array.
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; i++) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Certificate example
function certSample() {
let encodingBlob = {
// Convert the certificate data string to a Uint8Array.
data: stringToUint8Array(certData),
// Certificate format. Only PEM and DER are supported. In this example, the certificate is in PEM format.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
// Create an X509Cert instance.
cryptoCert.createX509Cert(encodingBlob, function (err, x509Cert) {
if (err != null) {
// Failed to create the X509Cert instance.
Console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message);
return;
}
// The X509Cert instance is successfully created.
Console.log("createX509Cert success");
// Obtain the certificate version.
let version = x509Cert.getVersion();
// Obtain the serialized data of the certificate.
x509Cert.getEncoded(function (err, data) {
if (err != null) {
// Failed to obtain the serialized data of the certificate.
Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The serialized data of the certificate is successfully obtained.
Console.log("getEncoded success");
}
});
// Obtain the certificate public key.
x509Cert.getPublicKey(function (err, pubKey) {
if (err != null) {
// Failed to obtain the certificate public key.
Console.log("getPublicKey failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The certificate public key is successfully obtained.
Console.log("getPublicKey success");
}
});
// Obtain the public key object using the getPublicKey() of the upper-level certificate object or this (self-signed) certificate object.
let pubKey = null;
// Verify the certificate signature.
x509Cert.verify(pubKey, function (err, data) {
if (err == null) {
// The signature verification is successful.
Console.log("verify success");
} else {
// The signature verification failed.
Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message);
}
});
// Time represented in a string.
let date = "150527000001Z";
// Verify the certificate validity period.
x509Cert.checkValidityWithDate(date, function (err, data) {
if (err != null) {
// Failed to verify the certificate validity period.
Console.log("checkValidityWithDate failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The certificate validity period is verified successfully.
Console.log("checkValidityWithDate success");
}
});
});
}
```
## Using the CRL
**When to Use**
Typical operations involve the following:
1. Parse the X.509 CRL data to create an **X509Crl** instance.
2. Obtain the CRL information, such as the CRL version and type.
3. Obtain the serialized data of the CRL.
4. Check whether the certificate is revoked.
5. Verify the CRL signature.
6. Obtain the revoked certificates.
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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 | getType() : string | Obtains the CRL type. |
| 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 | getIssuerName() : DataBlob | Obtains the CRL issuer. |
| 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. |
| X509Crl | getSignature() : DataBlob | Obtains the CRL signature. |
| X509Crl | getSignatureAlgName() : string | Obtains the CRL signing algorithm. |
| X509Crl | getSignatureAlgOid() : string | Obtains the signing algorithm OID of the CRL. |
| X509Crl | getSignatureAlgParams() : DataBlob | Obtains the signing algorithm parameters of the CRL. |
**How to Develop**
Example: Parse the X.509 CRL data to create an **X509Crl** instance and call APIs to perform CRL operations.
```javascript
import cryptoCert from '@ohos.security.cert';
import cryptoFramework from '@ohos.security.cryptoFramework';
// CRL data, which is only an example. The CRL data varies with the service.
let crlData = "-----BEGIN X509 CRL-----\n"
+ "MIIBijB0AgEBMA0GCSqGSIb3DQEBCwUAMBMxETAPBgNVBAMMCHJvb3QtY2ExFw0y\n"
+ "MDA2MTkxNjE1NDhaFw0yMDA3MTkxNjE1NDhaMBwwGgIJAMsozRATnap1Fw0yMDA2\n"
+ "MTkxNjEyMDdaoA8wDTALBgNVHRQEBAICEAIwDQYJKoZIhvcNAQELBQADggEBACPs\n"
+ "9gQB+djaXPHHRmAItebZpD3iJ/e36Dxr6aMVkn9FkI8OVpUI4RNcCrywyCZHQJte\n"
+ "995bbPjP7f1sZstOTZS0fDPgJ5SPAxkKOQB+SQnBFrlZSsxoUNU60gRqd2imR0Rn\n"
+ "1r09rP69F6E4yPc9biEld+llLGgoImP3zPOVDD6fbfcvVkjStY3bssVEQ/vjp4a3\n"
+ "/I12U7ZnSe3jaKqaQBoVJppkTFOIOq7IOxf5/IkMPmvRHDeC2IzDMzcUxym0dkny\n"
+ "EowHrjzo0bZVqpHMA2YgKZuwTpVLHk9GeBEK2hVkIoPVISkmiU4HFg0S6z68C5yd\n"
+ "DrAA7hErVgXhtURLbAI=\n"
+ "-----END X509 CRL-----\n";
// Convert the string into a Uint8Array.
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; i++) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Example of a CRL.
function crlSample() {
let encodingBlob = {
// Convert the CRL data from a string to a Uint8Array.
data: stringToUint8Array(crlData),
// CRL format. Only PEM and DER are supported. In this example, the CRL is in PEM format.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
// Create an X509Crl instance.
cryptoCert.createX509Crl(encodingBlob, function (err, x509Crl) {
if (err != null) {
// Failed to create the X509Crl instance.
Console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message);
return;
}
// The X509Crl instance is successfully created.
Console.log("createX509Crl success");
// Obtain the CRL version.
let version = x509Crl.getVersion();
// Obtain the serialized data of the CRL.
x509Crl.getEncoded(function (err, data) {
if (err != null) {
// Failed to obtain the serialized CRL data.
Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The serialized CRL data is successfully obtained.
Console.log("getEncoded success");
}
});
// Create an X509Cert instance by using createX509Cert() of cryptoFramework.
let x509Cert = null;
// Check whether the certificate is revoked.
x509Crl.isRevoked(x509Cert, function (err, isRevoked) {
if (err != null) {
// The operation fails.
Console.log("isRevoked failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The operation is successful.
Console.log("isRevoked success, isRevoked? " + isRevoked);
}
});
// Obtain the PubKey instance by using generateKeyPair() or convertKey() of AsyKeyGenerator. The process is omitted here.
let pubKey = null;
// Verify the CRL signature.
x509Crl.verify(pubKey, function (err, data) {
if (err == null) {
// The operation is successful.
Console.log("verify success");
} else {
// The operation fails.
Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message);
}
});
// Certificate serial number, which must be set based on the service.
let serialNumber = 1000;
// Obtain the revoked certificate based on the serial number.
x509Crl.getRevokedCert(serialNumber, function (err, entry) {
if (err != null) {
// The operation fails.
Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The operation is successful.
Console.log("getRevokedCert success");
}
});
});
}
```
## Verifying Certificate Chains
**When to Use**
You need to use the certificate chain validator in certificate chain verification.
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
| Instance | API | Description |
| ------------------ | ------------------------------------------------------------ | -------------------------------- |
| cryptoCert | createCertChainValidator(algorithm :string) : CertChainValidator | Creates a **CertChainValidator** instance.|
| 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. |
| CertChainValidator | algorithm : string | Obtains the certificate chain validator algorithm. |
**How to Develop**
Example: Create a **CertChainValidator** instance and verify the certificate chain.
```javascript
import cryptoCert from '@ohos.security.cert';
// CA certificate data, which is only an example. The CA certificate data varies with the service.
let caCertData = "-----BEGIN CERTIFICATE-----\n"
+ "...\n"
+ "...\n"
+ "...\n"
+ "-----END CERTIFICATE-----\n";
// End-entity certificate data, which is only an example. The certificate data varies with the service.
let secondCaCertData = "-----BEGIN CERTIFICATE-----\n"
+ "...\n"
+ "...\n"
+ "...\n"
+ "-----END CERTIFICATE-----\n";
// Convert the certificate data form a string to a Uint8Array.
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; i++) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Certificate chain validator example. In this example, a two-level certificate chain is verified.
function certChainValidatorSample() {
// Certificate chain validator algorithm. Currently, only PKIX is supported.
let algorithm = "PKIX";
// Create a CertChainValidator instance.
let validator = cryptoCert.createCertChainValidator(algorithm);
// CA certificate data.
let uint8ArrayOfCaCertData = stringToUint8Array(caCertData);
// Length of the CA certificate data.
let uint8ArrayOfCaCertDataLen = new Uint8Array(new Uint16Array([uint8ArrayOfCaCertData.byteLength]).buffer);
// End-entity certificate data.
let uint8ArrayOf2ndCaCertData = stringToUint8Array(secondCaCertData);
// Length of the end-entity certificate data.
let uint8ArrayOf2ndCaCertDataLen = new Uint8Array(new Uint16Array([uint8ArrayOf2ndCaCertData.byteLength]).buffer);
// Certificate chain binary data: end-entity certificate data length + end-entity certificate data + CA certificate data length + CA certificate data (in L-V format).
let encodingData = new Uint8Array(uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length +
uint8ArrayOfCaCertDataLen.length + uint8ArrayOfCaCertData.length);
for (var i = 0; i < uint8ArrayOf2ndCaCertDataLen.length; i++) {
encodingData[i] = uint8ArrayOf2ndCaCertDataLen[i];
}
for (var i = 0; i < uint8ArrayOf2ndCaCertData.length; i++) {
encodingData[uint8ArrayOf2ndCaCertDataLen.length + i] = uint8ArrayOf2ndCaCertData[i];
}
for (var i = 0; i < uint8ArrayOfCaCertDataLen.length; i++) {
encodingData[uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length + i] = uint8ArrayOfCaCertDataLen[i];
}
for (var i = 0; i < uint8ArrayOfCaCertData.length; i++) {
encodingData[uint8ArrayOf2ndCaCertDataLen.length + uint8ArrayOf2ndCaCertData.length +
uint8ArrayOfCaCertDataLen.length + i] = uint8ArrayOfCaCertData[i];
}
let certChainData = {
// Uint8Array type: L-V format (certificate data length-certificate data)
data: encodingData,
// Number of certificates. It is 2 in this example.
count: 2,
// Certificate format. PEM and DER are supported. In this example, the certificate is in PEM format.
encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
// Verify the certificate chain.
validator.validate(certChainData, function (err, data) {
if (err != null) {
// The operation fails.
Console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The operation is successful.
Console.log("validate success");
}
});
}
```
## Managing Revoked Certificates
**When to Use**
Typical operations involve the following:
1. Obtain a revoked certificate instance.
2. Obtain information, such as the serial number, issuer, and certificate revocation date, of the revoked certificate.
3. Obtain the serialized data of the revoked certificate.
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
| Instance | API | Description |
| ------------ | ----------------------------------------------------------- | ------------------------------------------ |
| 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
import cryptoCert from '@ohos.security.cert';
// Example of a revoked certificate.
function crlEntrySample() {
// Create an **X509Crl** instance by using createX509Crl() of cryptoFramework.
let x509Crl = null;
// Obtain a revoked certificate instance. In this example, the instance is obtained by using getRevokedCert().
let serialNumber = 1000;
x509Crl.getRevokedCert(serialNumber, function (err, crlEntry) {
if (err != null) {
// Failed to obtain the revoked certificate instance.
Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message);
return;
}
// The revoked certificate instance is successfully obtained.
Console.log("getRevokedCert success");
// Obtain the serial number of the revoked certificate.
let serialNumber = crlEntry.getSerialNumber();
// Obtain the revocation date of the revoked certificate.
crlEntry.getRevocationDate(function (err, date) {
if (err != null) {
// Failed to obtain the revocation date.
Console.log("getRevocationDate failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The revocation date is successfully obtained.
Console.log("getRevocationDate success, date is: " + date);
}
});
// Obtain the serialized data of the revoked certificate instance.
crlEntry.getEncoded(function (err, data) {
if (err != null) {
// Failed to obtain the serialized data.
Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message);
} else {
// The serialized data is successfully obtained.
Console.log("getEncoded success");
}
});
});
}
```
# Certificate Overview
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.
# Crypto Framework Development
> **NOTE**
>
> 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.
```javascript
import cryptoFramework from '@ohos.security.cryptoFramework';
function generateAsyKey() {
// Create an AsyKeyGenerator instance.
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
// Use the key generator to randomly generate an asymmetric key pair.
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let pubKey = globalKeyPair.pubKey;
let priKey = globalKeyPair.priKey;
// Obtain the binary data of the asymmetric key pair.
pkBlob = pubKey.getEncoded();
skBlob = priKey.getEncoded();
AlertDialog.show({ message : "pk bin data" + pkBlob.data} );
AlertDialog.show({ message : "sk bin data" + skBlob.data} );
})
}
```
Example 2: Randomly generate a symmetric key and obtain its binary data.
1. Create a **SymKeyGenerator** instance.
2. Randomly generate a symmetric key using **SymKeyGenerator**.
3. Obtain binary data of the key generated.
For example, randomly generate an AES key (256 bits) using promise-based APIs.
```javascript
import cryptoFramework from '@ohos.security.cryptoFramework';
// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
function testGenerateAesKey() {
// Create a SymKeyGenerator instance.
let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256');
// Use the key generator to randomly generate a symmetric key.
let promiseSymKey = symKeyGenerator.generateSymKey();
promiseSymKey.then( key => {
// Obtain the binary data of the symmetric key and output a 256-bit byte stream.
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
})
}
```
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.
```javascript
import cryptoFramework from '@ohos.security.cryptoFramework';
function convertAsyKey() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024");
let pkval = new Uint8Array([48,129,159,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,129,141,0,48,129,137,2,129,129,0,174,203,113,83,113,3,143,213,194,79,91,9,51,142,87,45,97,65,136,24,166,35,5,179,42,47,212,79,111,74,134,120,73,67,21,19,235,80,46,152,209,133,232,87,192,140,18,206,27,106,106,169,106,46,135,111,118,32,129,27,89,255,183,116,247,38,12,7,238,77,151,167,6,102,153,126,66,28,253,253,216,64,20,138,117,72,15,216,178,37,208,179,63,204,39,94,244,170,48,190,21,11,73,169,156,104,193,3,17,100,28,60,50,92,235,218,57,73,119,19,101,164,192,161,197,106,105,73,2,3,1,0,1]);
let pkBlob = {data : pkval};
rsaGenerator.convertKey(pkBlob, null, function(err, keyPair) {
if (keyPair == null) {
AlertDialog.show({message : "Convert keypair fail"});
}
AlertDialog.show({message : "Convert KeyPair success"});
})
}
```
**NOTE**
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.
```javascript
function convertEccAsyKey() {
let pubKeyArray = new Uint8Array([4,196,55,233,100,227,224,38,38,5,128,81,53,112,129,7,59,189,116,105,182,87,190,85,31,248,172,116,213,7,206,85,190,65,169,193,138,173,232,187,74,54,78,251,29,131,192,223,251,227,170,138,80,7,98,193,216,168,235,114,255,188,70,134,104]);
let priKeyArray = new Uint8Array([255,70,89,220,189,19,41,157,175,173,83,60,74,216,195,96,24,181,231,23,112,247,150,126,15,155,24,79,33,97,31,225]);
let pubKeyBlob = { data: pubKeyArray };
let priKeyBlob = { data: priKeyArray };
let generator = cryptoFrameWork.createAsyKeyGenerator("ECC256");
generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => {
if (error) {
AlertDialog.show({message : "Convert keypair fail"});
}
AlertDialog.show({message : "Convert KeyPair success"});
})
}
```
Example 5: Generate a symmetric key from binary key data.
1. Create a **SymKeyGenerator** instance.
2. Generate a symmetric key from the binary data passed in.
3. Obtain binary data of the key generated.
For example, generate a 3DES key (192 bits only) using callback-based APIs.
```javascript
import cryptoFramework from '@ohos.security.cryptoFramework';
// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
function testConvertAesKey() {
// Create a SymKeyGenerator instance.
let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
// Generate a symmetric key based on the specified data.
let keyMaterialBlob = genKeyMaterialBlob();
try {
symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => {
if (error) { // If the service logic fails to be executed, return the error information in the first parameter of the callback.
console.error(`convertKey error, ${error.code}, ${error.message}`);
return;
}
console.info(`key algName: ${key.algName}`);
console.info(`key format: ${key.format}`);
let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output a 192-bit byte stream.
console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data));
})
} catch (error) { // Throw an exception immediately in synchronous mode when an error is detected during the parameter check.
console.error(`convertKey failed, ${error.code}, ${error.message}`);
return;
}
}
```
## Encrypting and Decrypting Data
**When to Use**
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.
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
function genGcmParamsSpec() {
let arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0 , 0, 0]; // 12 bytes
let dataIv = new Uint8Array(arr);
let ivBlob = {data : dataIv};
arr = [0, 0, 0, 0 , 0, 0, 0, 0]; // 8 bytes
let dataAad = new Uint8Array(arr);
let aadBlob = {data : dataAad};
arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes
let dataTag = new Uint8Array(arr);
let tagBlob = {data : dataTag};
let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algoName : "GcmParamsSpec"};
return gcmParamsSpec;
}
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Convert byte streams into strings in plaintext.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// Output the byte streams in hexadecimal format.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
// Automatically generate a key in AES GCM mode and return the result in a promise.
function testAesGcm() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('testAesGcm');
}, 10)
}).then(() => {
// Create a SymKeyGenerator instance.
let symAlgoName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// Use the key generator to randomly generate a 128-bit symmetric key.
let promiseSymKey = symKeyGenerator.generateSymKey();
// Constructor
globalGcmParams = genGcmParamsSpec();
// Create a Cipher instance.
let cipherAlgoName = 'AES128|GCM|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgoName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
return promiseSymKey;
}).then(key => {
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
globalKey = key;
return key;
}).then(key => {
// Initialize the cipher environment and start encryption.
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
let promiseInit = globalCipher.init(mode, key, globalGcmParams); // init
return promiseInit;
}).then(() => {
let plainText = {data : stringToUint8Array('this is test!')};
let promiseUpdate = globalCipher.update(plainText); // update
return promiseUpdate;
}).then(updateOutput => {
globalCipherText = updateOutput;
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
}).then(authTag => {
// Obtain the authentication information after encryption.
globalGcmParams.authTag = authTag;
return;
}).then(() => {
// Initialize the cipher environment and start decryption.
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init
return promiseInit;
}).then(() => {
let promiseUpdate = globalCipher.update(globalCipherText); // update
return promiseUpdate;
}).then(updateOutput => {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
}).then(finalOutput => {
if (finalOutput == null) {
console.info('GCM finalOutput is null');
}
}).catch(error => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
```
For example, 3DES ECB is used. Generate a key from the existing data to encrypt and decrypt data using callback-based APIs.
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Convert byte streams into strings in plaintext.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// Output the byte streams in hexadecimal format.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
// For example, 3DES ECB is used. Use existing data to generate a key to encrypt and decrypt data, and return the result in a callback.
function test3DesEcb() {
// Create a SymKeyGenerator instance.
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// Create a Cipher instance.
let cipherAlgoName = '3DES192|ECB|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgoName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
// Generate a symmetric key based on the specified data.
let keyMaterialBlob = genKeyMaterialBlob();
try {
symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => {
if (error) {
console.error(`convertKey error, ${error.code}, ${error.message}`);
return;
}
console.info(`key algName: ${key.algName}`);
console.info(`key format: ${key.format}`);
let encodedKey = key.getEncoded();
console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data));
globalKey = key;
// Initialize the cipher environment and start encryption.
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
// init
globalCipher.init(mode, key, null, (err, ) => {
let plainText = {data : stringToUint8Array('this is test!')};
// update
globalCipher.update(plainText, (err, updateOutput) => {
globalCipherText = updateOutput;
//doFinal
globalCipher.doFinal(null, (err, finalOutput) => {
if (error) {
console.error(`doFinal error, ${error.code}, ${error.message}`);
return;
}
if (finalOutput != null) {
globalCipherText = Array.from(globalCipherText.data);
finalOutput = Array.from(finalOutput.data);
globalCipherText = globalCipherText.concat(finalOutput);
globalCipherText = new Uint8Array(globalCipherText);
globalCipherText = {data : globalCipherText};
}
// Initialize the cipher environment and start decryption.
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
// init
globalCipher.init(mode, globalKey, null, (err, ) => {
// update
globalCipher.update(globalCipherText, (err, updateOutput) => {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
// doFinal
globalCipher.doFinal(null, (error, finalOutput) => {
if (finalOutput != null) {
console.info("decrypt plainText:" + uint8ArrayToString(finalOutput.data));
}
})
})
})
})
})
})
})
} catch (error) {
console.error(`convertKey failed, ${error.code}, ${error.message}`);
return;
}
}
```
Example 2: Encrypt and decrypt data using an asymmetric key pair.
1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair.
2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode.
3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let plan = "This is cipher test.";
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;
}
function encryptMessageProMise() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then(rsaKeyPair => {
let pubKey = rsaKeyPair.pubKey;
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
}).then(() => {
let input = { data : stringToUint8Array(plan) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
}
function encryptMessageCallback() {
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) };
cipher.doFinal(input, function (err, data) {
console.info("EncryptOutPut is " + data.data);
})
})
})
}
```
**NOTE**
- 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.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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";
let plan2 = "This is Sign test plan1";
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);
}).then(() => {
return signer.sign(input2);
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
});
}
function verifyMessagePromise() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
}
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) {
signer.sign(input2, function (err, data) {
SignMessageBlob = data;
console.info("sign output is " + SignMessageBlob.data);
});
});
});
});
}
function verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
console.info("verify result is " + data);
});
});
})
}
```
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.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
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";
let plan2 = "This is Sign test plan1";
let input1 = { data : stringToUint8Array(plan1) };
let input2 = { data : stringToUint8Array(plan2) };
function signMessagePromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let signer = cryptoFramework.createSign("ECC256|SHA256");
let keyGenPromise = eccGenerator.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 verifyMessagePromise() {
let verifyer = cryptoFramework.createVerify("ECC256|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
}
function signMessageCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let signer = cryptoFramework.createSign("ECC256|SHA256");
eccGenerator.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 verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("ECC256|SHA256");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
console.info("verify result is " + data);
});
});
})
}
```
## Generating a Digest
**When to Use**
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).
| 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 | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. |
| Md | readonly algName : string; | Obtains the digest algorithm. |
**How to Develop**
1. Call **createMd()** to create an **Md** instance.
2. Call **update()** to update the data for computing a digest. **update()** can be called multiple times to update the data by segment.
3. Call **digest()** to compute a digest.
4. Obtain the digest algorithm and length of the digest generated.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// Convert string into uint8Arr.
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// Generate a dataBlob of the given length.
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
}
// Compute a message digest using promise-based APIs.
function doMdByPromise(algName) {
var md;
try {
md = cryptoFramework.createMd(algName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Promise]: Md algName is: " + md.algName);
var promiseMdUpdate = md.update(GenDataBlob(12));
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Promise]: MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// Compute a message digest using callback-based APIs.
function doMdByCallback(algName) {
var md;
try {
md = cryptoFramework.createMd(algName);
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Callback]: Md algName is: " + md.algName);
md.update(GenDataBlob(12), (err,) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
md.digest((err1, mdOutput) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
} else {
console.error("[Callback]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Callback]: MD len: " + mdLen);
}
});
});
}
```
## Performing Key Agreement
**When to Use**
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.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair;
function ecdhPromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyGenPromise = eccGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
return eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey);
}).then((secret) => {
console.info("ecdh output is " + secret.data);
}).catch((error) => {
console.error("ecdh error.");
});
}
function ecdhCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256");
eccGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, function (err, secret) {
if (err) {
console.error("ecdh error.");
return;
}
console.info("ecdh output is " + secret.data);
});
});
}
```
## Generating a MAC
**When to Use**
A message authentication code (MAC) can be used to verify both the integrity and authenticity of a message using a shared secret.
Typical MAC operations involve the following:
1. Create a **Mac** instance.
2. Initialize the **Mac** instance, add one or more segments of data for generating a MAC, and generate a MAC.
3. Obtain the algorithm and length of a MAC.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
| 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. |
| 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.
4. Call **doFinal()** to generate a MAC.
5. Obtain the algorithm and length of the MAC.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// Convert string into uint8Arr.
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// Generate a blob.
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
}
// Generate a MAC using promise-based APIs.
function doHmacByPromise(algName) {
var mac;
try {
mac = cryptoFramework.createMac(algName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Promise]: Mac algName is: " + mac.algName);
var KeyBlob = {
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
var promiseMacUpdate = mac.update(GenDataBlob(12));
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// Generate a MAC using callback-based APIs.
function doHmacByCallback(algName) {
var mac;
try {
mac = cryptoFramework.createMac(algName);
} 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 KeyBlob = {
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
}
mac.update(GenDataBlob(12), (err2, ) => {
if (err2) {
console.error("[Callback]: err: " + err2.code);
}
mac.doFinal((err3, macOutput) => {
if (err3) {
console.error("[Callback]: err: " + err3.code);
} else {
console.error("[Callback]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Callback]: MAC len: " + macLen);
}
});
});
});
});
}
```
## Generating Random Numbers
**When to Use**
Typical random number operations involve the following:
1. Generate a random number.
2. Set a seed based on the random number generated.
**Available APIs**
For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
| 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. |
**How to Develop**
1. Call **createRandom()** to create a **Random** instance.
2. Call **generateRandom()** to generate a random number of the given length.
3. Call **setSeed()** to set a seed.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// Generate a random number and set a seed using promise-based APIs.
function doRandByPromise(len) {
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
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");
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// Generate a random number and set a seed using callback-based APIs.
function doRandByCallback(len) {
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
rand.generateRandom(len, (err, randData) => {
if (err) {
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");
}
});
}
});
}
```
# 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.
## Working Principles
The crypto framework provides components in the following layers:
- Interface layer: provides unified JS interface externally.
- Plugin layer: implements third-party algorithm libraries.
- 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:
|Algorithm|Block Cipher Mode|Algorithm String|
|---|---|---|
|3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]|
|AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]|
> **NOTE**
>
> The options included in the square brackets ([]) are mutually exclusive.
**Asymmetric RSA Encryption and Decryption**
The following padding modes are involved in RSA encryption and decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**.
- When **NoPadding** is used, you can specify the following parameters:
[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|NoPadding
- When **PKCS1** is used, you can specify the following parameters:
[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1
- When **PKCS1_OAEP** is used, you can specify the following parameters:
[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1_OAEP|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512]
> **NOTE**
>
> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values.
### Signing and Signature Verification Specifications
**RSA Signing and Signature Verification**
The following padding modes are involved in RSA encryption and decryption: **PKCS1** and **PSS**.
- When **PKCS1** is used, you can specify the following parameters:
[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]
- When **PSS** is used, you can specify the following parameters:
[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PSS|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512]
> **NOTE**
>
> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values.
**ECDSA Signing and Signature Verification**
The following ECDSA parameters are supported:
|Asymmetric Key Algorithm|Supported Types|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
|Digest Algorithm|Supported Types|
|---|---|
|HASH|SHA-1|
|HASH|SHA-224|
|HASH|SHA-256|
|HASH|SHA-384|
|HASH|SHA-512|
### Key Agreement Specifications
**ECDH**
The following ECDH parameters are supported:
|Asymmetric Key Algorithm|Supported Types|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
### MD Algorithm Specifications
The crypto framework supports only MD5.
### SHA Algorithm Specifications
The crypto framework supports only SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册