未验证 提交 9272e359 编写于 作者: 胡啸天 提交者: Gitee

arkts modify

Signed-off-by: N胡啸天 <huxiaotian2@huawei.com>
上级 0d8d2498
......@@ -51,7 +51,7 @@
以使用Promise方式随机生成RSA密钥(1024位,素数个数为2)为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
function generateAsyKey() {
......@@ -81,25 +81,18 @@ function generateAsyKey() {
以使用Promise方式随机生成AES密钥(256位)为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
// 字节流以16进制输出
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 => {
// 获取对称密钥的二进制数据,输出长度为256bit,以16进制表示,长度为64,即32字节
// Obtain the binary data of the symmetric key and output the 256-bit key. The length is 32 bytes.
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
console.info('key hex:' + encodedKey.data);
})
}
```
......@@ -111,13 +104,13 @@ function testGenerateAesKey() {
1. 获取RSA公钥或私钥二进制数据,公钥需满足ASN.1语法、X.509规范、DER编码格式,私钥需满足ASN.1语法、PKCS#8规范、DER编码格式。
2. 创建AsyKeyGenerator对象,调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。
```js
```ts
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 };
let pkBlob: cryptoFramework.DataBlob = { data: pkVal };
rsaGenerator.convertKey(pkBlob, null, (err, keyPair) => {
if (err) {
AlertDialog.show({ message: 'Convert keyPair fail' });
......@@ -139,14 +132,14 @@ function convertAsyKey() {
1. 获取ECC二进制密钥数据,封装成DataBlob对象。
2. 调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
function convertEccAsyKey() {
let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7, 3, 66, 0, 4, 83, 96, 142, 9, 86, 214, 126, 106, 247, 233, 92, 125, 4, 128, 138, 105, 246, 162, 215, 71, 81, 58, 202, 121, 26, 105, 211, 55, 130, 45, 236, 143, 55, 16, 248, 75, 167, 160, 167, 106, 2, 152, 243, 44, 68, 66, 0, 167, 99, 92, 235, 215, 159, 239, 28, 106, 124, 171, 34, 145, 124, 174, 57, 92]);
let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56, 137, 35, 207, 0, 60, 191, 90, 61, 136, 105, 210, 16, 27, 4, 171, 57, 10, 61, 123, 40, 189, 28, 34, 207, 236, 22, 45, 223, 10, 189, 160, 10, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7]);
let pubKeyBlob = { data: pubKeyArray };
let priKeyBlob = { data: priKeyArray };
let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray };
let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray };
let generator = cryptoFramework.createAsyKeyGenerator('ECC256');
generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => {
if (error) {
......@@ -168,17 +161,10 @@ function convertEccAsyKey() {
以使用callback方式生成3DES密钥(3DES密钥只能为192位)为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
// 字节流以16进制输出
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
function genKeyMaterialBlob() {
function genKeyMaterialBlob(): cryptoFramework.DataBlob {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
......@@ -188,23 +174,25 @@ function genKeyMaterialBlob() {
}
function testConvertSymKey() {
// 生成对称密钥生成器
// 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) { // 业务逻辑执行错误通过callback的第一个参数返回错误信息,即抛出异步异常
console.error(`convertKey error, ${error.code}, ${error.message}`);
if (error) { // If the service logic fails to be executed, the first parameter of callback returns error information, that is, an exception is thrown asynchronously.
let e: BusinessError = error as BusinessError;
console.error(`convertKey error, ${e.code}, ${e.message}`);
return;
}
console.info(`key algName: ${key.algName}`);
console.info(`key format: ${key.format}`);
let encodedKey = key.getEncoded(); // 获取对称密钥的二进制数据,输出长度为192bit的字节流,以16进制表示,长度为48,即24字节
console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data));
let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output in bytes array. The length is 24 bytes.
console.info('key getEncoded hex: ' + encodedKey.data);
})
} catch (error) { // 参数检查的错误以同步的方式立即抛出异常
console.error(`convertKey failed, ${error.code}, ${error.message}`);
} catch (error) { // Throw an exception immediately when an error is detected in parameter check.
let e: BusinessError = error as BusinessError;
console.error(`convertKey failed, ${e.code}, ${e.message}`);
return;
}
}
......@@ -224,18 +212,18 @@ function testConvertSymKey() {
以使用Promise方式随机生成SM2密钥(256位)为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
function generateAsyKey() {
// 创建非对称密钥生成器
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// 通过非对称密钥生成器,随机生成非对称密钥
let keyGenPromise = rsaGenerator.generateKeyPair();
function generateSM2Key() {
// Create an AsyKeyGenerator instance.
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// Use the key generator to randomly generate an asymmetric key pair.
let keyGenPromise = sm2Generator.generateKeyPair();
keyGenPromise.then(keyPair => {
let pubKey = keyPair.pubKey;
let priKey = keyPair.priKey;
// 获取非对称密钥的二进制数据
// Obtain the binary data of the asymmetric key pair.
let pkBlob = pubKey.getEncoded();
let skBlob = priKey.getEncoded();
AlertDialog.show({ message: "pk bin data" + pkBlob.data });
......@@ -258,25 +246,18 @@ function generateAsyKey() {
以使用Promise方式随机生成SM4密钥(128位)为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
// 字节流以16进制输出
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
function testGenerateSM4Key() {
// 创建对称密钥生成器
// Create a SymKeyGenerator instance.
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("SM4_128");
// 通过密钥生成器随机生成对称密钥
// Use the key generator to randomly generate a symmetric key.
let promiseSymKey = symKeyGenerator.generateSymKey();
promiseSymKey.then(key => {
// 获取对称密钥的二进制数据,输出长度为128bit的字节流,以16进制表示,长度为32,即16字节
// Obtain the binary data of the symmetric key and output a 128-bit byte stream. The length is 16 bytes.
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
console.info('key hex:' + encodedKey.data);
})
}
```
......@@ -292,22 +273,22 @@ function testGenerateSM4Key() {
1. 获取SM2二进制密钥数据,封装成DataBlob对象。
2. 调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
function convertSM2AsyKey() {
let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,129,28,207,85,1,130,45,3,66,0,4,90,3,58,157,190,248,76,7,132,200,151,208,112,230,96,140,90,238,211,155,128,109,248,40,83,214,78,42,104,106,55,148,249,35,61,32,221,135,143,100,45,97,194,176,52,73,136,174,40,70,70,34,103,103,161,99,27,187,13,187,109,244,13,7]);
let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,54,41,239,240,63,188,134,113,31,102,149,203,245,89,15,15,47,202,170,60,38,154,28,169,189,100,251,76,112,223,156,159,160,10,6,8,42,129,28,207,85,1,130,45]);
let pubKeyBlob = { data: pubKeyArray };
let priKeyBlob = { data: priKeyArray };
let generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => {
if (error) {
AlertDialog.show({message : "Convert keypair fail"});
return;
}
AlertDialog.show({message : "Convert KeyPair success"});
})
let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 3, 66, 0, 4, 90, 3, 58, 157, 190, 248, 76, 7, 132, 200, 151, 208, 112, 230, 96, 140, 90, 238, 211, 155, 128, 109, 248, 40, 83, 214, 78, 42, 104, 106, 55, 148, 249, 35, 61, 32, 221, 135, 143, 100, 45, 97, 194, 176, 52, 73, 136, 174, 40, 70, 70, 34, 103, 103, 161, 99, 27, 187, 13, 187, 109, 244, 13, 7]);
let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 54, 41, 239, 240, 63, 188, 134, 113, 31, 102, 149, 203, 245, 89, 15, 15, 47, 202, 170, 60, 38, 154, 28, 169, 189, 100, 251, 76, 112, 223, 156, 159, 160, 10, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45]);
let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray };
let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray };
let generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => {
if (error) {
AlertDialog.show({ message: "Convert keypair fail" });
return;
}
AlertDialog.show({ message: "Convert KeyPair success" });
})
}
```
......@@ -351,30 +332,38 @@ function convertSM2AsyKey() {
以使用Promise方式根据密钥参数生成ECC密钥为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
// 打印bigint信息
function showBigIntInfo(bnName, bnValue) {
console.warn(bnName + ":");
console.warn(". 十进制: " + bnValue.toString());
console.warn(". 16进制: " + bnValue.toString(16));
console.warn(". 长度(bits): " + bnValue.toString(2).length);
// Print bigint information.
function showBigIntInfo(bnName: string, bnValue: bigint | string | number) {
if (typeof bnValue === 'string') {
console.error('type is string');
return;
}
if (typeof bnValue === 'number') {
console.error('type is number');
return;
}
console.info(bnName + ":");
console.info(". Decimal: " + bnValue.toString());
console.info(". Hexadecimal: " + bnValue.toString(16));
console.info(". Length (bits): " + bnValue.toString(2).length);
}
// 根据密钥参数属性,构造ECC公私钥共有参数的sepc结构体
function genEccCommonSpec() {
let fieldFp = {
// Construct the EccCommonSpec struct based on the key specifications. The EccCommonSpec struct defines the common parameters of the ECC private key and public key.
function genEccCommonSpec(): cryptoFramework.ECCCommonParamsSpec {
let fieldFp: cryptoFramework.ECFieldFp = {
fieldType: "Fp",
p: BigInt("0xffffffffffffffffffffffffffffffff000000000000000000000001")
}
let G = {
let G: cryptoFramework.Point = {
x: BigInt("0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"),
y: BigInt("0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34")
}
let eccCommonSpec = {
let eccCommonSpec: cryptoFramework.ECCCommonParamsSpec = {
algName: "ECC",
specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC,
field: fieldFp,
......@@ -387,8 +376,8 @@ function genEccCommonSpec() {
return eccCommonSpec;
}
// 打印ECC密钥参数属性
function showEccSpecDetailInfo(key, keyType) {
// Print the ECC key specifications.
function showEccSpecDetailInfo(key: cryptoFramework.PubKey | cryptoFramework.PriKey, keyType: string) {
console.info("show detail of " + keyType + ":");
try {
let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
......@@ -436,22 +425,22 @@ function showEccSpecDetailInfo(key, keyType) {
}
}
// 测试根据ECC公私钥公共密钥参数生成ECC密钥对,并获得其密钥参数属性
// Generate an ECC key pair based on the EccCommonSpec instance and obtain the key specifications.
function testEccUseCommKeySpecGet() {
try {
let commKeySpec = genEccCommonSpec(); // 使用参数属性,构造ECC公私钥公共密钥参数对象
let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(commKeySpec); // 使用密钥参数对象创建生成器
let keyPairPromise = generatorBySpec.generateKeyPair(); // 使用生成器创建ECC密钥对
let commKeySpec = genEccCommonSpec(); // Construct the EccCommonSpec object.
let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(commKeySpec); // Create an AsyKeyGenerator instance based on the EccCommonSpec object.
let keyPairPromise = generatorBySpec.generateKeyPair(); // Generate an ECC key pair.
keyPairPromise.then(keyPair => {
showEccSpecDetailInfo(keyPair.priKey, "priKey"); // 对私钥获取相关密钥参数属性
showEccSpecDetailInfo(keyPair.pubKey, "pubKey"); // 对公钥获取相关密钥参数属性
}).catch(error => {
// 逻辑错误等异步异常在此捕获
showEccSpecDetailInfo(keyPair.priKey, "priKey"); // Obtain the ECC specifications of the private key.
showEccSpecDetailInfo(keyPair.pubKey, "pubKey"); // Obtain the ECC specifications of the public key.
}).catch((error: BusinessError) => {
// Capture exceptions such as logic errors asynchronously here.
console.error("generateComm error");
console.error("error code: " + error.code + ", message is: " + error.message);
})
} catch (error) {
// 参数错误等同步异常在此捕获
// Capture parameter errors synchronously here.
console.error("testEccUseCommSpec error");
console.error("error code: " + error.code + ", message is: " + error.message);
}
......@@ -467,11 +456,15 @@ function testEccUseCommKeySpecGet() {
3. 获取密钥对象的密钥参数属性。
以使用Callback方式根据密钥参数生成RSA公钥为例:
```js
```ts
// RSA公钥密钥参数生成函数
function genRsaPubKeySpec(nIn: bigint, eIn: bigint) {
let rsaCommSpec = { n: nIn, algName: "RSA", specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC };
let rsaPubKeySpec = {
function genRsaPubKeySpec(nIn: bigint, eIn: bigint): cryptoFramework.RSAPubKeySpec {
let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = {
n: nIn,
algName: "RSA",
specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
};
let rsaPubKeySpec: cryptoFramework.RSAPubKeySpec = {
params: rsaCommSpec,
pk: eIn,
algName: "RSA",
......@@ -480,15 +473,23 @@ function genRsaPubKeySpec(nIn: bigint, eIn: bigint) {
return rsaPubKeySpec;
}
// 根据密钥参数属性,构造RSA公钥密钥参数对象
// Construct an RSA public key specifications object based on the key parameters.
function genRsa2048PubKeySpec() {
let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25");
let eIn = BigInt("0x010001");
return genRsaPubKeySpec(nIn, eIn);
}
// 将RSA公钥密钥参数属性与预期值比较
function compareRsaPubKeyBySpec(rsaKeySpec, n, e) {
// Compare the RSA public key specifications with the expected values.
function compareRsaPubKeyBySpec(rsaKeySpec: cryptoFramework.RSAPubKeySpec, n: bigint | string | number, e: bigint | string | number) {
if (typeof n === 'string' || typeof e === 'string') {
console.error('type is string');
return;
}
if (typeof n === 'number' || typeof e === 'number') {
console.error('type is number');
return;
}
if (rsaKeySpec.params.n != n) {
return false;
}
......@@ -498,7 +499,7 @@ function compareRsaPubKeyBySpec(rsaKeySpec, n, e) {
return true;
}
// 测试根据RSA公钥密钥参数生成RSA公钥,并获得其密钥参数属性,与预期值做比较
// Generate an RSA public key based on the RSA public key specifications, obtain the key specifications, and compare the key specifications with the expected values.
function rsaUsePubKeySpecGetCallback() {
let rsaPubKeySpec = genRsa2048PubKeySpec();
let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaPubKeySpec);
......@@ -559,49 +560,44 @@ function rsaUsePubKeySpecGetCallback() {
3. 创建加解密生成器。
4. 通过加解密生成器加密或解密数据。
```js
```ts
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 };
let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
arr = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 bytes
let dataAad = new Uint8Array(arr);
let aadBlob = { data: dataAad };
let aadBlob: cryptoFramework.DataBlob = { 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 }; // GCM的authTag在加密时从doFinal结果中获取,在解密时填入init函数的params参数中
let gcmParamsSpec = { iv: ivBlob, aad: aadBlob, authTag: tagBlob, algName: "GcmParamsSpec" };
let tagBlob: cryptoFramework.DataBlob = {
data: dataTag
}; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption.
let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
iv: ivBlob,
aad: aadBlob,
authTag: tagBlob,
algName: "GcmParamsSpec"
};
return gcmParamsSpec;
}
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 字节流以16进制输出
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array) {
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
......@@ -611,75 +607,58 @@ function uint8ArrayToString(array) {
// AES GCM模式示例,自动生成密钥(promise写法)
function testAesGcm() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('testAesGcm');
}, 10)
}).then(() => {
// 生成对称密钥生成器
let symAlgName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// 通过密钥生成器随机生成128位长度的对称密钥
let promiseSymKey = symKeyGenerator.generateSymKey();
// 构造参数
globalGcmParams = genGcmParamsSpec();
// 生成加解密生成器
let cipherAlgName = 'AES128|GCM|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgName);
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));
let symAlgName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// Generate GCM parameter specifications.
let globalGcmParams = genGcmParamsSpec();
// Create a Cipher instance.
let cipherAlgName = 'AES128|GCM|PKCS7';
let globalCipher = cryptoFramework.createCipher(cipherAlgName);
console.info(`cipher algName: ${globalCipher.algName}`);
// Use the key generator to randomly generate a 128-bit symmetric key.
let globalCipherText: cryptoFramework.DataBlob;
let globalKey: cryptoFramework.SymKey;
let promiseSymKey = symKeyGenerator.generateSymKey();
promiseSymKey.then(key => {
// Initialize the Cipher instance and start encryption.
globalKey = key;
return key;
}).then(key => {
// 初始化加解密操作环境:开始加密
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 => {
// GCM模式需要从doFinal的输出中取出加密后的认证信息并填入globalGcmParams,在解密时传入init()
globalGcmParams.authTag = authTag;
return;
}).then(() => {
// 初始化加解密操作环境:开始解密
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) { // 使用finalOutput.data前,先判断结果是否为null
console.info('GCM finalOutput is null');
}
}).catch(error => {
console.error(`catch error, ${error.code}, ${error.message}`);
return globalCipher.init(mode, globalKey, globalGcmParams);
})
.then(() => {
let plainText: cryptoFramework.DataBlob = { data: stringToUint8Array('this is test!') };
return globalCipher.update(plainText);
})
.then((updateOutput: cryptoFramework.DataBlob): Promise<cryptoFramework.DataBlob> => {
globalCipherText = updateOutput;
return globalCipher.doFinal(null);
})
.then(tag => {
// In GCM mode, the encrypted authentication information needs to be obtained from the output of doFinal() and passed in globalGcmParams of init() in decryption.
globalGcmParams.authTag = tag;
return;
})
.then(() => {
// Initialize the Cipher instance and start decryption.
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
return globalCipher.init(mode, globalKey, globalGcmParams);
})
.then(() => {
return globalCipher.update(globalCipherText); // update
})
.then((updateOutput: cryptoFramework.DataBlob): Promise<cryptoFramework.DataBlob> => {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
return globalCipher.doFinal(null);
})
.then(finalOutput => {
if (finalOutput == null) { // Check whether the result is null before using finalOutput.data.
console.info('GCM finalOutput is null');
}
})
.catch((error: BusinessError) => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
```
......@@ -692,32 +671,20 @@ function testAesGcm() {
3. 创建加解密生成器。
4. 通过加解密生成器加密或解密数据。
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 字节流以16进制输出
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array) {
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
......@@ -725,18 +692,18 @@ function uint8ArrayToString(array) {
return arrayString;
}
function genKeyMaterialBlob() {
function genKeyMaterialBlob(): cryptoFramework.DataBlob {
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)
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
return { data: keyMaterial };
}
// 3DES ECB模式示例,采用已有数据生成密钥(callback写法)
// Generate a 3DES ECB key from the existing data in callback mode.
function test3DesEcb() {
// 生成对称密钥生成器
// Create a SymKeyGenerator instance.
let symAlgName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
if (symKeyGenerator == null) {
......@@ -745,17 +712,11 @@ function test3DesEcb() {
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// 生成加解密生成器
// Create a Cipher instance.
let cipherAlgName = '3DES192|ECB|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
let globalCipher = cryptoFramework.createCipher(cipherAlgName);
// 根据指定的数据,生成对称密钥
// Generate a symmetric key based on the specified data.
let keyMaterialBlob = genKeyMaterialBlob();
try {
symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => {
......@@ -766,31 +727,30 @@ function test3DesEcb() {
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;
console.info('key getEncoded: ' + encodedKey.data);
let globalKey = key;
// 初始化加解密操作环境:开始加密
// Initialize the Cipher instance and start encryption.
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
// init
globalCipher.init(mode, key, null, (err,) => {
let plainText = { data: stringToUint8Array('this is test!') };
let plainText: cryptoFramework.DataBlob = { data: stringToUint8Array('this is test!') };
// update
globalCipher.update(plainText, (err, updateOutput) => {
globalCipherText = updateOutput;
let globalCipherText = updateOutput;
//doFinal
globalCipher.doFinal(null, (err, finalOutput) => {
if (error) {
console.error(`doFinal error, ${error.code}, ${error.message}`);
if (err) {
console.error(`doFinal error, ${err.code}, ${err.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 };
let tmpCipherText = Array.from(globalCipherText.data);
let tmpFinalOutput = Array.from(finalOutput.data);
tmpCipherText = tmpCipherText.concat(tmpFinalOutput);
globalCipherText = { data: new Uint8Array(tmpCipherText) };
}
// 初始化加解密操作环境:开始解密
// Initialize the Cipher instance and start decryption.
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
// init
globalCipher.init(mode, globalKey, null, (err,) => {
......@@ -799,7 +759,7 @@ function test3DesEcb() {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
// doFinal
globalCipher.doFinal(null, (error, finalOutput) => {
if (finalOutput != null) { // 使用finalOutput.data前,先判断结果是否为null
if (finalOutput != null) { // Check whether the result is null before using finalOutput.data.
console.info('decrypt plainText: ' + uint8ArrayToString(finalOutput.data));
}
})
......@@ -827,40 +787,44 @@ function test3DesEcb() {
以AES GCM以promise方式,分段update()实现加解密为例:
```js
```ts
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
var globalPlainText;
function genGcmParamsSpec() {
let arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0 , 0, 0]; // 12 bytes
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};
let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
arr = [0, 0, 0, 0 , 0, 0, 0, 0]; // 8 bytes
arr = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 bytes
let dataAad = new Uint8Array(arr);
let aadBlob = {data : dataAad};
let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes
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, algName : "GcmParamsSpec"};
let tagBlob: cryptoFramework.DataBlob = {
data: dataTag
}; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption.
let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
iv: ivBlob,
aad: aadBlob,
authTag: tagBlob,
algName: "GcmParamsSpec"
};
return gcmParamsSpec;
}
// 字节流以16进制输出
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr[i] = str.charCodeAt(i);
}
return arr;
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array) {
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
......@@ -868,63 +832,45 @@ function uint8ArrayToString(array) {
return arrayString;
}
// 算法库不限定update的次数和每次加解密的数据量,业务可根据自身内存情况对明文/密文进行多次分段。
function testAesMultiUpdate() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('testAesMultiUpdate');
}, 10)
}).then(() => {
// 生成对称密钥生成器
let symAlgName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// 通过密钥生成器随机生成128位长度的对称密钥
let promiseSymKey = symKeyGenerator.generateSymKey();
// 构造参数
globalGcmParams = genGcmParamsSpec();
// 生成加解密生成器
let cipherAlgName = 'AES128|GCM|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
return promiseSymKey;
let symAlgName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// Generate GCM parameter specifications.
let globalGcmParams = genGcmParamsSpec();
// Create a Cipher instance.
let cipherAlgName = 'AES128|GCM|PKCS7';
let globalCipher = cryptoFramework.createCipher(cipherAlgName);
console.info(`cipher algName: ${globalCipher.algName}`);
// Use the key generator to randomly generate a 128-bit symmetric key.
let globalCipherText: cryptoFramework.DataBlob;
let globalKey: cryptoFramework.SymKey;
let globalPlainText = '';
let promiseSymKey = symKeyGenerator.generateSymKey();
promiseSymKey.then(key => {
// Initialize the Cipher instance and start encryption.
globalKey = key;
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
return globalCipher.init(mode, globalKey, globalGcmParams);
})
.then(key => {
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
globalKey = key;
return key;
})
.then(key => {
// 初始化加解密操作环境:开始加密
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
let promiseInit = globalCipher.init(mode, key, globalGcmParams); // init
return promiseInit;
})
.then(async () => {
let plainText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设明文总共43字节
let messageArr = [];
let updateLength = 20; // 假设每20字节分段update一次
globalCipherText = [];
let plainText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the plaintext is of 43 bytes.
let messageArr: number[] = [];
let updateLength = 20; // Pass in 20 bytes by update() each time.
let tmpCipherText = new Uint8Array();
for (let i = 0; i <= plainText.length; i++) {
if ((i % updateLength == 0 || i == plainText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob = { data: message };
let updateOutput = await globalCipher.update(messageBlob); // 分段update
// 把update的结果拼接起来,得到密文(有些情况下还需拼接doFinal的结果,这取决于分组模式
// 和填充模式,本例中GCM模式的doFinal结果只包含authTag而不含密文,所以不需要拼接)
globalCipherText = globalCipherText.concat(Array.from(updateOutput.data));
let messageBlob: cryptoFramework.DataBlob = { data: message };
let updateOutput = await globalCipher.update(messageBlob); // Update by segment.
// Combine the result of each update() to obtain the ciphertext. In certain cases, the doFinal() results need to be combined, which depends on the cipher block mode
// and padding mode you use. In this example, the doFinal() result in GCM mode contains authTag but not ciphertext. Therefore, there is no need to combine the results.
let mergeText = new Uint8Array(tmpCipherText.length + updateOutput.data.length);
mergeText.set(tmpCipherText);
mergeText.set(updateOutput.data, tmpCipherText.length);
tmpCipherText = mergeText;
// tmpCipherText = tmpCipherText.concat(Array.from(updateOutput.data));
messageArr = [];
}
if (i < plainText.length) {
......@@ -933,45 +879,41 @@ function testAesMultiUpdate() {
}
return;
})
.then(() => {
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
.then((): Promise<cryptoFramework.DataBlob> => {
return globalCipher.doFinal(null);
})
.then(authTag => {
// 获取加密后的认证信息
globalGcmParams.authTag = authTag;
.then(tag => {
// In GCM mode, the encrypted authentication information needs to be obtained from the output of doFinal() and passed in globalGcmParams of init() in decryption.
globalGcmParams.authTag = tag;
return;
})
.then(() => {
// 初始化加解密操作环境:开始解密
// Initialize the Cipher instance and start decryption.
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init
return promiseInit;
return globalCipher.init(mode, globalKey, globalGcmParams);
})
.then(async () => {
let updateLength = 20;
let updateTimes = Math.ceil(globalCipherText.length / updateLength); // 上取整
globalPlainText = "";
let updateTimes = Math.ceil(globalCipherText.data.length / updateLength); // Round up to the nearest integer.
for (let i = 0; i < updateTimes; i++) {
let messageArr = globalCipherText.slice(i * updateLength, (i + 1) * updateLength);
let messageArr = globalCipherText.data.slice(i * updateLength, (i + 1) * updateLength);
let message = new Uint8Array(messageArr);
let messageBlob = { data: message };
let updateOutput = await globalCipher.update(messageBlob); // 分段update
globalPlainText += uint8ArrayToString(updateOutput.data); // 恢复出原始明文
let messageBlob: cryptoFramework.DataBlob = { data: message };
let updateOutput = await globalCipher.update(messageBlob); // Update by segment.
globalPlainText += uint8ArrayToString(updateOutput.data); // Restore the original plaintext.
}
return;
})
.then(() => {
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
.then((): Promise<cryptoFramework.DataBlob> => {
return globalCipher.doFinal(null);
})
.then(finalOutput => {
if (finalOutput == null) {
if (finalOutput == null) { // Check whether the result is null before using finalOutput.data.
console.info('GCM finalOutput is null');
}
console.info(`decrypt output: ${globalPlainText}`);
})
.catch(error => {
.catch((error: BusinessError) => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
......@@ -985,99 +927,99 @@ function testAesMultiUpdate() {
2. 生成Cipher对象。通过createCipher接口创建Cipher对象,执行初始化操作,设置密钥及加解密模式。
3. 执行加解密操作。通过调用Cipher对象提供的doFinal接口,执行加密操作生成密文或执行解密操作生成明文。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
let plan = "This is cipher test.";
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 以Promise方式加密
// Encrypt the message in promise mode.
function encryptMessagePromise() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
// 生成加解密生成器
// Create a Cipher instance.
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
// 通过非对称秘钥生成器生成非对称密钥对
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then(rsaKeyPair => {
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
let pubKey = rsaKeyPair.pubKey;
// 初始化加解密操作环境:使用公钥开始加密
// Initialize the Cipher instance and use the public key to encrypt the data.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
}).then(() => {
// doFinal
let input = { data: stringToUint8Array(plan) };
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
return cipher.doFinal(input);
}).then(dataBlob => {
// 获取加密后的信息
// Obtain the encrypted data.
console.info("EncryptOutPut is " + dataBlob.data);
});
}
// 以Callback方式加密
// Encrypt the message in callback mode.
function encryptMessageCallback() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
// 生成加解密生成器
// Create a Cipher instance.
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
// 通过非对称秘钥生成器生成非对称密钥对
rsaGenerator.generateKeyPair(function (err, keyPair) {
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
rsaGenerator.generateKeyPair((err, keyPair) => {
let pubKey = keyPair.pubKey;
// 初始化加解密操作环境:使用公钥开始加密
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
let input = { data: stringToUint8Array(plan) };
// Initialize the Cipher instance and use the public key to encrypt the data.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, (err, data) => {
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
// doFinal
cipher.doFinal(input, function (err, data) {
// 获取加密后的信息
cipher.doFinal(input, (err, data) => {
// Obtain the encrypted data.
console.info("EncryptOutPut is " + data.data);
})
})
})
}
// 以Promise方式加解密
// Encrypt and decrypt the message in promise mode.
function decryptMessagePromise() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
// 生成加解密生成器,用于加密
// Create a Cipher instance for encryption.
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
// 生成加解密生成器,用于解密
// Create a Cipher instance for decryption.
let decoder = cryptoFramework.createCipher("RSA1024|PKCS1");
// 通过非对称秘钥生成器生成非对称密钥对
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
let keyGenPromise = rsaGenerator.generateKeyPair();
let keyPair;
let cipherDataBlob;
let input = { data: stringToUint8Array(plan) };
keyGenPromise.then(rsaKeyPair => {
let keyPair: cryptoFramework.KeyPair;
let cipherDataBlob: cryptoFramework.DataBlob;
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
keyPair = rsaKeyPair;
// 初始化加解密操作环境:使用公钥开始加密
// Initialize the Cipher instance and use the public key to encrypt the message.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
})
.then(() => {
// 加密doFinal
// Call doFinal() to encrypt data.
return cipher.doFinal(input);
})
.then(dataBlob => {
// 获取加密后的信息,并用于解密的入参
.then((dataBlob: cryptoFramework.DataBlob): Promise<void> => {
// Obtain the encrypted information and use it as the input parameter for decryption.
console.info("EncryptOutPut is " + dataBlob.data);
AlertDialog.show({ message: "output" + dataBlob.data });
cipherDataBlob = dataBlob;
// 初始化加解密操作环境:使用私钥开始解密
// Initialize the Cipher instance and use the private key to decrypt the message.
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
})
.then(() => {
// 解密doFinal
// Call doFinal() to decrypt the message.
return decoder.doFinal(cipherDataBlob);
})
.then(decodeData => {
// 验证解密后,数据与原先数据是否保持一致
// Check whether the decrypted data is consistent with the original data.
if (decodeData.data.toString() === input.data.toString()) {
AlertDialog.show({ message: "decrypt success" });
return;
......@@ -1086,33 +1028,31 @@ function decryptMessagePromise() {
});
}
// 以Callback方式加解密
// Encrypt and decrypt the message in callback mode.
function decryptMessageCallback() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
// 生成加解密生成器,用于加密
// Create a Cipher instance for encryption.
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
// 生成加解密生成器,用于解密
// Create a Cipher instance for decryption.
let decoder = cryptoFramework.createCipher("RSA1024|PKCS1");
let plainText = "this is cipher text";
let input = { data: stringToUint8Array(plainText) };
let cipherData;
let keyPair;
// 通过非对称秘钥生成器生成非对称密钥对
rsaGenerator.generateKeyPair(function (err, newKeyPair) {
keyPair = newKeyPair;
// 初始化加解密操作环境:使用公钥开始加密
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, function (err, data) {
// 加密doFinal
cipher.doFinal(input, function (err, data) {
// 获取加密后的信息,并用于解密的入参
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plainText) };
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
rsaGenerator.generateKeyPair((err, newKeyPair) => {
let keyPair = newKeyPair;
// Initialize the Cipher instance and use the public key to encrypt the message.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, (err, data) => {
// Call doFinal() to encrypt the message.
cipher.doFinal(input, (err, data) => {
// Obtain the encrypted information and use it as the input parameter for decryption.
AlertDialog.show({ message: "EncryptOutPut is " + data.data });
cipherData = data;
// 初始化加解密操作环境:使用私钥开始解密
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, function (err, data) {
// 解密doFinal
decoder.doFinal(cipherData, function (err, data) {
// 验证解密后,数据与原先数据是否保持一致
let cipherData = data;
// Initialize the Cipher instance and use the private key to decrypt the message.
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, (err, data) => {
// Call doFinal() to decrypt the message.
decoder.doFinal(cipherData, (err, data) => {
// Check whether the decrypted data is consistent with the original data.
if (input.data.toString() === data.data.toString()) {
AlertDialog.show({ message: "decrype success" });
return;
......@@ -1134,20 +1074,20 @@ function decryptMessageCallback() {
2. 生成Cipher对象。通过createCipher接口创建Cipher对象,执行初始化操作,设置密钥及加解密模式。
3. 执行加解密操作。通过调用Cipher对象提供的doFinal接口,执行加密操作生成密文或执行解密操作生成明文,多次调用doFinal实现分段。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array) {
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
......@@ -1157,65 +1097,73 @@ function uint8ArrayToString(array) {
function encryptLongMessagePromise() {
let globalPlainText = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
let globalCipherOutput;
let globalDecodeOutput;
var globalKeyPair;
let plainTextSplitLen = 64; // RSA每次加解密允许的原文长度大小与密钥位数和填充模式等有关,详细规格内容见overview文档
let cipherTextSplitLen = 128; // RSA密钥每次加密生成的密文数据长度计算方式:密钥位数/8
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
let globalKeyPair: cryptoFramework.KeyPair;
let plainTextSplitLen = 64; // The length of the plaintext to be encrypted or decrypted each time by RSA depends on the number of key bits and padding mode. For details, see the Crypto Framework Overview.
let cipherTextSplitLen = 128; // Length of the ciphertext = Number of key bits/8
let keyGenName = "RSA1024";
let cipherAlgName = "RSA1024|PKCS1";
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // 创建非对称密钥生成器对象
let cipher = cryptoFramework.createCipher(cipherAlgName); // 创建加密Cipher对象
let decoder = cryptoFramework.createCipher(cipherAlgName); // 创建解密Decoder对象
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("testRsaMultiDoFinal");
}, 10);
}).then(() => {
return asyKeyGenerator.generateKeyPair(); // 生成rsa密钥
}).then(keyPair => {
globalKeyPair = keyPair; // 保存到密钥对全局变量
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object.
let cipher = cryptoFramework.createCipher(cipherAlgName); // Create a Cipher object.
let decoder = cryptoFramework.createCipher(cipherAlgName); // Create a Decoder object.
let keyGenPromise = asyKeyGenerator.generateKeyPair(); // Generate an RSA key pair.
let globalCipherText: cryptoFramework.DataBlob;
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
globalKeyPair = rsaKeyPair; // Save the key pair as a global variable.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
}).then(async () => {
globalCipherOutput = [];
// 将原文按64字符进行拆分,循环调用doFinal进行加密,使用1024bit密钥时,每次加密生成128B长度的密文
for (let i = 0; i < (globalPlainText.length / plainTextSplitLen); i++) {
let tempStr = globalPlainText.substr(i * plainTextSplitLen, plainTextSplitLen);
let tempBlob = { data : stringToUint8Array(tempStr) };
let tempCipherOutput = await cipher.doFinal(tempBlob);
globalCipherOutput = globalCipherOutput.concat(Array.from(tempCipherOutput.data));
}
console.info(`globalCipherOutput len is ${globalCipherOutput.length}, data is: ${globalCipherOutput.toString()}`);
return;
}).then(() =>{
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
}).then(async() => {
globalDecodeOutput = [];
// 将密文按128B进行拆分解密,得到原文后进行拼接
for (let i = 0; i < (globalCipherOutput.length / cipherTextSplitLen); i++) {
let tempBlobData = globalCipherOutput.slice(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
let message = new Uint8Array(tempBlobData);
let tempBlob = { data : message };
let tempDecodeOutput = await decoder.doFinal(tempBlob);
globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);
}
if (globalDecodeOutput === globalPlainText) {
console.info(`encode and decode success`);
} else {
console.info(`encode and decode error`);
}
return;
}).catch(error => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
.then(async () => {
let tmpCipherText = new Uint8Array();
// Split the plaintext by 64 characters and cyclically call doFinal() to encrypt the plaintext. If a 1024-bit key is used, 128-byte ciphertext is generated each time.
for (let i = 0; i < (globalPlainText.length / plainTextSplitLen); i++) {
let tempStr = globalPlainText.substr(i * plainTextSplitLen, plainTextSplitLen);
let tempBlob: cryptoFramework.DataBlob = { data: stringToUint8Array(tempStr) };
let tempCipherOutput = await cipher.doFinal(tempBlob);
let mergeText = new Uint8Array(tmpCipherText.length + tempCipherOutput.data.length);
mergeText.set(tmpCipherText);
mergeText.set(tempCipherOutput.data, tmpCipherText.length);
tmpCipherText = mergeText;
}
globalCipherText = { data: tmpCipherText };
console.info(`globalCipherOutput len is ${tmpCipherText.length}, data is: ${tmpCipherText.toString()}`);
return;
})
.then((): Promise<void> => {
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
})
.then(async () => {
let tmpDecodeText = new Uint8Array();
// Split and decrypt the ciphertext by 128 bytes, and combine the plaintext obtained each time.
for (let i = 0; i < (globalCipherText.data.length / cipherTextSplitLen); i++) {
let tempBlobData = globalCipherText.data.slice(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
let message = new Uint8Array(tempBlobData);
let tempBlob: cryptoFramework.DataBlob = { data: message };
let tempDecodeOutput = await decoder.doFinal(tempBlob);
let mergeText = new Uint8Array(tmpDecodeText.length + tempDecodeOutput.data.length);
mergeText.set(tmpDecodeText);
mergeText.set(tempDecodeOutput.data, tmpDecodeText.length);
tmpDecodeText = mergeText;
}
let globalDecodeOutput = uint8ArrayToString(tmpDecodeText);
if (globalDecodeOutput === globalPlainText) {
console.info(`encode and decode success`);
} else {
console.info(`encode and decode error`);
}
return;
})
.catch((error: BusinessError) => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
```
> **说明:**
......@@ -1232,22 +1180,26 @@ function encryptLongMessagePromise() {
2. 生成Cipher对象。通过createCipher接口创建Cipher对象,执行初始化操作,设置密钥及加解密模式,在Update前通过setCipherSpec设置PKCS1_OAEP填充字节流P。
3. 执行加解密操作。通过调用Cipher对象提供的doFinal接口,执行加密操作生成密文或执行解密操作生成明文,需要加解密Cipher对象的字节流P一致。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 根据密钥参数属性构造RSA非对称密钥对密钥参数
function genRsaKeyPairSpec(nIn: bigint, eIn: bigint, dIn: bigint) {
let rsaCommSpec = { n: nIn, algName: "RSA", specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC };
let rsaKeyPairSpec = {
let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = {
n: nIn,
algName: "RSA",
specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
};
let rsaKeyPairSpec: cryptoFramework.RSAKeyPairSpec = {
params: rsaCommSpec,
sk: dIn,
pk: eIn,
......@@ -1258,7 +1210,7 @@ function genRsaKeyPairSpec(nIn: bigint, eIn: bigint, dIn: bigint) {
}
// 生成RSA2048密钥对参数
function genRsa2048KeyPairSpec() {
function genRsa2048KeyPairSpec(): cryptoFramework.RSAKeyPairSpec {
let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25");
let eIn = BigInt("0x010001");
let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1");
......@@ -1267,35 +1219,35 @@ function genRsa2048KeyPairSpec() {
function rsaUseSpecDecryptOAEPPromise() {
let plan = "This is cipher test.";
// 获得RSA密钥对密钥参数对象
// Obtain the key parameter object of the RSA key pair.
let rsaKeyPairSpec = genRsa2048KeyPairSpec();
// 根据RSA密钥对参数生成RSA密钥对
// Generate an RSA key pair based on the RSA key parameters.
let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec);
let keyGenPromise = rsaGeneratorSpec.generateKeyPair();
let cipher = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1");
let decoder = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1");
let keyPair;
let cipherDataBlob;
// RSA加解密PKCS1-OAEP模式填充字节流P
let keyPair: cryptoFramework.KeyPair;
let cipherDataBlob: cryptoFramework.DataBlob;
// Set the pSource, which defines the encoding input P filled by OAEP.
let pSource = new Uint8Array([1, 2, 3, 4]);
let input = { data: stringToUint8Array(plan) };
// 生成密钥
keyGenPromise.then(rsaKeyPair => {
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
// Generate the key pair.
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
keyPair = rsaKeyPair;
// 进行加密操作初始化
// Initialize the Cipher instance for encryption.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
})
.then(() => {
// get和set操作可以放在Cipher对象init之后,此处对cipher进行set和get操作
// Set and obtain the cipher specifications after the initialization.
cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
let retP = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
// 比较get出来的P字节流与set进去的P字节流是否一致
// Check whether the obtained PSource is the same as the PSource set.
if (retP.toString() != pSource.toString()) {
AlertDialog.show({ message: "error init pSource" + retP });
} else {
console.info("pSource changed ==" + retP);
}
// 进行OAEP其他参数的get操作
// Obtain other OAEP parameters.
let md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
console.info("md == " + md);
let mgf = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
......@@ -1304,33 +1256,33 @@ function rsaUseSpecDecryptOAEPPromise() {
console.info("mgf1Md == " + mgf1Md);
return cipher.doFinal(input);
})
.then(dataBlob => {
.then((dataBlob: cryptoFramework.DataBlob): Promise<void> => {
console.info("EncryptOutPut is " + dataBlob.data);
cipherDataBlob = dataBlob;
// get和set操作可以放在Cipher对象init之前,且与init之后等价,此处对decoder进行set和get操作
// The get() and set() operations can be performed before the init() operation of the Cipher object and are equivalent to those after the init() operation. For example, set and get the decoder.
decoder.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
let retP = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
// 比较get出来的P字节流与set进去的P字节流是否一致
// Check whether the obtained PSource is the same as the PSource set.
if (retP.toString() != pSource.toString()) {
AlertDialog.show({ message: "error init pSource" + retP });
} else {
console.info("pSource changed ==" + retP);
}
// 进行OAEP其他参数的get操作
// Obtain other OAEP parameters.
let md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
console.info("md == " + md);
let mgf = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
console.info("mgf == " + mgf);
let mgf1Md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR);
console.info("mgf1Md == " + mgf1Md);
// 初始化解密操作
// Initialize the decryption operation.
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
})
.then(() => {
return decoder.doFinal(cipherDataBlob);
})
.then(decodeData => {
// 解密成功
// The decryption is successful.
if (decodeData.data.toString() === input.data.toString()) {
console.info("oaep decrypt success");
AlertDialog.show({ message: " oaep decrypt success" });
......@@ -1353,99 +1305,99 @@ function rsaUseSpecDecryptOAEPPromise() {
2. 生成Cipher对象。通过createCipher接口创建Cipher对象,执行初始化操作,设置密钥及加解密模式。
3. 执行加解密操作。通过调用Cipher对象提供的doFinal接口,执行加密操作生成密文或执行解密操作生成明文。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
let plan = "This is cipher test.";
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 以Promise方式加密
function encryptMessagePromise() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// 生成加解密生成器
// Create a Cipher instance.
let cipher = cryptoFramework.createCipher("SM2_256|SM3");
// 通过非对称秘钥生成器生成非对称密钥对
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
let keyGenPromise = sm2Generator.generateKeyPair();
keyGenPromise.then(sm2KeyPair => {
keyGenPromise.then((sm2KeyPair: cryptoFramework.KeyPair): Promise<void> => {
let pubKey = sm2KeyPair.pubKey;
// 初始化加解密操作环境:使用公钥开始加密
// Initialize the Cipher instance and use the public key to encrypt the message.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
}).then(() => {
// doFinal
let input = { data: stringToUint8Array(plan) };
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
return cipher.doFinal(input);
}).then(dataBlob => {
// 获取加密后的信息
// Obtain the encrypted data.
console.info("EncryptOutPut is " + dataBlob.data);
});
}
// 以Callback方式加密
// Encrypt the message in callback mode.
function encryptMessageCallback() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// 生成加解密生成器
// Create a Cipher instance.
let cipher = cryptoFramework.createCipher("SM2_256|SM3");
// 通过非对称秘钥生成器生成非对称密钥对
sm2Generator.generateKeyPair(function (err, keyPair) {
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
sm2Generator.generateKeyPair((err, keyPair) => {
let pubKey = keyPair.pubKey;
// 初始化加解密操作环境:使用公钥开始加密
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
let input = { data: stringToUint8Array(plan) };
// Initialize the Cipher instance and use the public key to encrypt the message.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, (err, data) => {
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
// doFinal
cipher.doFinal(input, function (err, data) {
// 获取加密后的信息
cipher.doFinal(input, (err, data) => {
// Obtain the encrypted data.
console.info("EncryptOutPut is " + data.data);
})
})
})
}
// 以Promise方式加解密
// Encrypt and decrypt data in promise mode.
function decryptMessagePromise() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// 生成加解密生成器,用于加密
// Create a Cipher instance for encryption.
let cipher = cryptoFramework.createCipher("SM2_256|SM3");
// 生成加解密生成器,用于解密
// Create a Cipher instance for decryption.
let decoder = cryptoFramework.createCipher("SM2_256|SM3");
// 通过非对称秘钥生成器生成非对称密钥对
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
let keyGenPromise = sm2Generator.generateKeyPair();
let keyPair;
let cipherDataBlob;
let input = { data: stringToUint8Array(plan) };
keyGenPromise.then(rsaKeyPair => {
let keyPair: cryptoFramework.KeyPair;
let cipherDataBlob: cryptoFramework.DataBlob;
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plan) };
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
keyPair = rsaKeyPair;
// 初始化加解密操作环境:使用公钥开始加密
// Initialize the Cipher instance and use the public key to encrypt the data.
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
})
.then(() => {
// 加密doFinal
// Call doFinal() to encrypt data.
return cipher.doFinal(input);
})
.then(dataBlob => {
// 获取加密后的信息,并用于解密的入参
.then((dataBlob: cryptoFramework.DataBlob): Promise<void> => {
// Obtain the encrypted information and use it as the input parameter for decryption.
console.info("EncryptOutPut is " + dataBlob.data);
AlertDialog.show({ message: "output" + dataBlob.data });
cipherDataBlob = dataBlob;
// 初始化加解密操作环境:使用私钥开始解密
// Initialize the Cipher instance and use the private key to decrypt the data.
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
})
.then(() => {
// 解密doFinal
// Call doFinal() to decrypt data.
return decoder.doFinal(cipherDataBlob);
})
.then(decodeData => {
// 验证解密后,数据与原先数据是否保持一致
// Check whether the decrypted data is consistent with the original data.
if (decodeData.data.toString() === input.data.toString()) {
AlertDialog.show({ message: "decrypt success" });
return;
......@@ -1454,33 +1406,33 @@ function decryptMessagePromise() {
});
}
// 以Callback方式加解密
// Encrypt and decrypt data in callback mode.
function decryptMessageCallback() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
// 生成加解密生成器,用于加密
// Create a Cipher instance for encryption.
let cipher = cryptoFramework.createCipher("SM2_256|SM3");
// 生成加解密生成器,用于解密
// Create a Cipher instance for decryption.
let decoder = cryptoFramework.createCipher("SM2_256|SM3");
let plainText = "this is cipher text";
let input = { data: stringToUint8Array(plainText) };
let cipherData;
let keyPair;
// 通过非对称秘钥生成器生成非对称密钥对
sm2Generator.generateKeyPair(function (err, newKeyPair) {
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plainText) };
let cipherData: cryptoFramework.DataBlob;
let keyPair: cryptoFramework.KeyPair;
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
sm2Generator.generateKeyPair((err, newKeyPair) => {
keyPair = newKeyPair;
// 初始化加解密操作环境:使用公钥开始加密
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, function (err, data) {
// 加密doFinal
cipher.doFinal(input, function (err, data) {
// 获取加密后的信息,并用于解密的入参
// Initialize the Cipher instance and use the public key to encrypt the data.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, (err, data) => {
// Call doFinal() to encrypt data.
cipher.doFinal(input, (err, data) => {
// Obtain the encrypted information and use it as the input parameter for decryption.
AlertDialog.show({ message: "EncryptOutPut is " + data.data });
cipherData = data;
// 初始化加解密操作环境:使用私钥开始解密
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, function (err, data) {
// 解密doFinal
decoder.doFinal(cipherData, function (err, data) {
// 验证解密后,数据与原先数据是否保持一致
// Initialize the Cipher instance and use the private key to decrypt the data.
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, (err, data) => {
// Call doFinal() to decrypt data.
decoder.doFinal(cipherData, (err, data) => {
// Check whether the decrypted data is consistent with the original data.
if (input.data.toString() === data.data.toString()) {
AlertDialog.show({ message: "decrype success" });
return;
......@@ -1507,19 +1459,20 @@ function decryptMessageCallback() {
3. 创建加解密生成器。
4. 通过加解密生成器加密或解密数据。
```js
```ts
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);
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr[i] = str.charCodeAt(i);
}
return arr;
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array) {
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
......@@ -1529,31 +1482,31 @@ function uint8ArrayToString(array) {
// SM4 ECB模式示例,callback写法
function testSM4Ecb() {
// 生成非对称密钥生成器
// Create an AsyKeyGenerator instance.
let sm4Generator = cryptoFramework.createSymKeyGenerator('SM4_128');
// 生成加解密生成器,用于加密
// Create a Cipher instance for encryption.
let cipher = cryptoFramework.createCipher("SM4_128|ECB|PKCS7");
// 生成加解密生成器,用于解密
// Create a Cipher instance for decryption.
let decoder = cryptoFramework.createCipher("SM4_128|ECB|PKCS7");
let plainText = "this is cipher text";
let input = { data: stringToUint8Array(plainText) };
let cipherData;
let key;
// 通过非对称秘钥生成器生成非对称密钥对
sm4Generator.generateSymKey(function (err, newKey) {
let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plainText) };
let cipherData: cryptoFramework.DataBlob;
let key: cryptoFramework.SymKey;
// Generate an asymmetric key pair using the AsyKeyGenerator instance.
sm4Generator.generateSymKey((err, newKey) => {
key = newKey;
// 初始化加解密操作环境:使用公钥开始加密
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, key, null, function (err, data) {
// 加密doFinal
cipher.doFinal(input, function (err, data) {
// 获取加密后的信息,并用于解密的入参
// Initialize the Cipher instance and use the public key to encrypt the data.
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, key, null, (err, data) => {
// Call doFinal() to encrypt data.
cipher.doFinal(input, (err, data) => {
// Obtain the encrypted information and use it as the input parameter for decryption.
AlertDialog.show({ message: "EncryptOutPut is " + data.data });
cipherData = data;
// 初始化加解密操作环境:使用私钥开始解密
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, key, null, function (err, data) {
// 解密doFinal
decoder.doFinal(cipherData, function (err, data) {
// 验证解密后,数据与原先数据是否保持一致
// Initialize the Cipher instance and use the private key to decrypt the data.
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, key, null, (err, data) => {
// Call doFinal() to decrypt data.
decoder.doFinal(cipherData, (err, data) => {
// Check whether the decrypted data is consistent with the original data.
if (input.data.toString() === data.data.toString()) {
AlertDialog.show({ message: "decrype success" });
return;
......@@ -1617,28 +1570,28 @@ function testSM4Ecb() {
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用verify接口传入签名进行验签。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
let globalKeyPair;
let SignMessageBlob;
let globalKeyPair: cryptoFramework.KeyPair;
let SignMessageBlob: cryptoFramework.DataBlob;
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan1";
let input1 = { data: stringToUint8Array(plan1) };
let input2 = { data: stringToUint8Array(plan2) };
let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
function signMessagePromise() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // API version 10开始,支持"RSA|PKCS1|SHA256"
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications.
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then(keyPair => {
globalKeyPair = keyPair;
......@@ -1654,7 +1607,7 @@ function signMessagePromise() {
});
}
// 调用完sign操作后调用verify
// Call verify() after sign() is called.
function verifyMessagePromise() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
......@@ -1669,8 +1622,8 @@ function verifyMessagePromise() {
function signMessageCallback() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // API version 10开始,支持"RSA|PKCS1|SHA256"
rsaGenerator.generateKeyPair(function (err, keyPair) {
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications.
rsaGenerator.generateKeyPair((err, keyPair) => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, err => {
......@@ -1684,12 +1637,12 @@ function signMessageCallback() {
});
}
// 调用完sign操作后调用verify
// Call verify() after sign() is called.
function verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
verifyer.init(globalKeyPair.pubKey, err => {
verifyer.update(input1, err => {
verifyer.verify(input2, SignMessageBlob, function (err, data) {
verifyer.verify(input2, SignMessageBlob, (err, data) => {
console.info("verify result is " + data);
});
});
......@@ -1707,24 +1660,24 @@ function verifyMessageCallback() {
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用doFinal接口传入签名进行验签。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
let globalKeyPair;
let SignMessageBlob;
let globalKeyPair: cryptoFramework.KeyPair;
let SignMessageBlob: cryptoFramework.DataBlob;
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan1";
let input1 = { data: stringToUint8Array(plan1) };
let input2 = { data: stringToUint8Array(plan2) };
let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
function signMessagePromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
......@@ -1759,7 +1712,7 @@ function verifyMessagePromise() {
function signMessageCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let signer = cryptoFramework.createSign("ECC256|SHA256");
eccGenerator.generateKeyPair(function (err, keyPair) {
eccGenerator.generateKeyPair((err, keyPair) => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, err => {
......@@ -1777,7 +1730,7 @@ function verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("ECC256|SHA256");
verifyer.init(globalKeyPair.pubKey, err => {
verifyer.update(input1, err => {
verifyer.verify(input2, SignMessageBlob, function (err, data) {
verifyer.verify(input2, SignMessageBlob, (err, data) => {
console.info("verify result is " + data);
});
});
......@@ -1795,69 +1748,69 @@ function verifyMessageCallback() {
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。多次通过Verify类提供的update接口,添加签名数据,并调用verify接口传入签名进行验签,完成分段验签。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
function signLongMessagePromise() {
let globalPlainText = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
let globalSignData;
let textSplitLen = 64; // 自定义的数据拆分长度
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
let globalSignData: Uint8Array;
let textSplitLen = 64; // Customized data splitting length.
let keyGenName = "RSA1024";
let signAlgName = "RSA1024|PKCS1|SHA256";
let globalKeyPair;
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // 创建非对称密钥生成器对象
let signer = cryptoFramework.createSign(signAlgName); // 创建签名Signer对象
let verifier = cryptoFramework.createVerify(signAlgName); // 创建验签Verifier对象
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("testRsaMultiUpdate");
}, 10);
}).then(() => {
return asyKeyGenerator.generateKeyPair(); // 生成RSA密钥
}).then(keyPair => {
globalKeyPair = keyPair; // 保存到密钥对全局变量
let globalKeyPair: cryptoFramework.KeyPair;
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object.
let signer = cryptoFramework.createSign(signAlgName); // Create a Signer instance.
let verifier = cryptoFramework.createVerify(signAlgName); // Create a Verifier instance.
let keyGenPromise = asyKeyGenerator.generateKeyPair();
keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
globalKeyPair = rsaKeyPair; // Save the key pair as a global variable.
return signer.init(globalKeyPair.priKey);
}).then(async () => {
// 当原文过大时,可将原文按理想长度进行拆分,循环调用update添加原文
for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) {
let tempStr = globalPlainText.substr(i * textSplitLen, textSplitLen);
let tempBlob = { data : stringToUint8Array(tempStr) };
await signer.update(tempBlob);
}
return signer.sign(null);
}).then(data =>{
globalSignData = data.data;
console.info(`globalSignOutput len is ${globalSignData.length}, data is: ${globalSignData.toString()}`);
return verifier.init(globalKeyPair.pubKey);
}).then(async() => {
// 当原文过大时,可将原文按理想长度进行拆分,循环调用update添加原文
for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) {
let tempData = globalPlainText.slice(i * textSplitLen, (i + 1) * textSplitLen);
let tempBlob = { data : stringToUint8Array(tempData) };
await verifier.update(tempBlob);
}
return verifier.verify(null, { data : globalSignData});
}).then(res => {
console.info(`verify res is ${res}`);
}).catch(error => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
.then(async () => {
// If the plaintext is too large, split the plaintext based on the specified length and cyclically call update() to pass in the plaintext.
for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) {
let tempStr = globalPlainText.substr(i * textSplitLen, textSplitLen);
let tempBlob: cryptoFramework.DataBlob = { data: stringToUint8Array(tempStr) };
await signer.update(tempBlob);
}
return signer.sign(null);
})
.then(data => {
globalSignData = data.data;
console.info(`globalSignOutput len is ${globalSignData.length}, data is: ${globalSignData.toString()}`);
return verifier.init(globalKeyPair.pubKey);
})
.then(async () => {
// If the plaintext is too large, split the plaintext based on the specified length and cyclically call update() to pass in the plaintext.
for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) {
let tempData = globalPlainText.slice(i * textSplitLen, (i + 1) * textSplitLen);
let tempBlob: cryptoFramework.DataBlob = { data: stringToUint8Array(tempData) };
await verifier.update(tempBlob);
}
return verifier.verify(null, { data: globalSignData });
})
.then(res => {
console.info(`verify res is ${res}`);
})
.catch((error: BusinessError) => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
```
......@@ -1871,22 +1824,35 @@ function signLongMessagePromise() {
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥,可以获得、设置PSS模式相关参数,验签成功需要保证盐值长度一致。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用verify接口传入签名进行验签。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array: Uint8Array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
// 根据密钥参数属性构造RSA非对称密钥对密钥参数
function genRsaKeyPairSpec(nIn: bigint, eIn: bigint, dIn: bigint) {
let rsaCommSpec = { n: nIn, algName: "RSA", specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC };
let rsaKeyPairSpec = {
let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = {
n: nIn,
algName: "RSA",
specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
};
let rsaKeyPairSpec: cryptoFramework.RSAKeyPairSpec = {
params: rsaCommSpec,
sk: dIn,
pk: eIn,
......@@ -1897,7 +1863,7 @@ function genRsaKeyPairSpec(nIn: bigint, eIn: bigint, dIn: bigint) {
}
// 生成RSA2048密钥对参数
function genRsa2048KeyPairSpec() {
function genRsa2048KeyPairSpec(): cryptoFramework.RSAKeyPairSpec {
let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25");
let eIn = BigInt("0x010001");
let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1");
......@@ -1907,21 +1873,21 @@ function genRsa2048KeyPairSpec() {
function verifyMessageCallbackPSS() {
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan1";
let input1 = { data: stringToUint8Array(plan1) };
let input2 = { data: stringToUint8Array(plan2) };
let globalKeyPair;
let signMessageBlob;
// 获得RSA密钥对密钥参数对象
let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
let globalKeyPair: cryptoFramework.KeyPair;
let signMessageBlob: cryptoFramework.DataBlob;
// Obtain the key parameter object of the RSA key pair.
let rsaKeyPairSpec = genRsa2048KeyPairSpec();
// 构造RSA密钥对生成器
// Create an RSA key pair generator.
let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec);
// sign和verfiy均支持RSA密钥带长度/不带长度的写法
// Both sign() and verify() support the RSA key with or without the length.
let signer = cryptoFramework.createSign("RSA|PSS|SHA256|MGF1_SHA256");
let verifyer = cryptoFramework.createVerify("RSA2048|PSS|SHA256|MGF1_SHA256");
rsaGeneratorSpec.generateKeyPair(function (err, keyPair) {
rsaGeneratorSpec.generateKeyPair((err, keyPair) => {
globalKeyPair = keyPair;
signer.init(globalKeyPair.priKey, err => {
// 在签名初始化后,对PSS参数进行set和get操作
// After the initialization, set and obtain the PSS parameters.
let setN = 32;
signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN);
let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM);
......@@ -1935,8 +1901,8 @@ function verifyMessageCallbackPSS() {
let mgf1Md = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MGF1_MD_STR);
console.info("mgf1Md == " + mgf1Md);
signer.update(input1, err => {
signer.sign(input2, function (err, data) {
// 在验签初始化前,对PSS参数进行set和get操作,功能与初始化后一致
signer.sign(input2, (err, data) => {
// Before signature verification initialization, set and obtain PSS parameters. The functions are the same as those after initialization.
signMessageBlob = data;
AlertDialog.show({ message: "res" + signMessageBlob.data });
let setN = 32;
......@@ -1953,7 +1919,7 @@ function verifyMessageCallbackPSS() {
console.info("mgf1Md == " + mgf1Md);
verifyer.init(globalKeyPair.pubKey, err => {
verifyer.update(input1, err => {
verifyer.verify(input2, signMessageBlob, function (err, data) {
verifyer.verify(input2, signMessageBlob, (err, data) => {
AlertDialog.show({ message: "res " + data });
})
});
......@@ -1979,41 +1945,38 @@ function verifyMessageCallbackPSS() {
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用doFinal接口传入签名进行验签。
```js
```ts
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;
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr[i] = str.charCodeAt(i);
}
return arr;
}
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan2";
let input1 = { data: stringToUint8Array(plan1) };
let input2 = { data: stringToUint8Array(plan2) };
let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
function signAndVerify() {
let signMessageBlob;
let globalKeyPair;
let signMessageBlob: cryptoFramework.DataBlob;
let sm2Generator = cryptoFramework.createAsyKeyGenerator("SM2_256");
let signer = cryptoFramework.createSign("SM2_256|SM3");
sm2Generator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
sm2Generator.generateKeyPair((err, keyPair) => {
let priKey = keyPair.priKey;
signer.init(priKey, err => {
signer.update(input1, err => {
signer.sign(input2, function (err, data) {
signer.sign(input2, (err, data) => {
signMessageBlob = data;
console.info("sign output is " + signMessageBlob.data);
let verifyer = cryptoFramework.createVerify("SM2_256|SM3");
verifyer.init(globalKeyPair.pubKey, err => {
verifyer.init(keyPair.pubKey, err => {
verifyer.update(input1, err => {
verifyer.verify(input2, signMessageBlob, function (err, data) {
verifyer.verify(input2, signMessageBlob, (err, data) => {
console.info("verify result is " + data);
AlertDialog.show({ message: "verify success" })
});
......@@ -2053,21 +2016,21 @@ function signAndVerify() {
1. 生成ECC密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成ECC非对称密钥。
2. 基于ECC密钥的私钥及公钥执行ECDH操作。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
let globalKeyPair;
let globalKeyPair: cryptoFramework.KeyPair;
function ecdhPromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); // API version 10开始,支持输入"ECC"来进行密钥协商
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); // ECC is supported for key agreement from API version 10.
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) => {
}).catch((error: BusinessError) => {
console.error("ecdh error.");
});
}
......@@ -2075,9 +2038,9 @@ function ecdhPromise() {
function ecdhCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256");
eccGenerator.generateKeyPair(function (err, keyPair) {
eccGenerator.generateKeyPair((err, keyPair) => {
globalKeyPair = keyPair;
eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, function (err, secret) {
eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, (err, secret) => {
if (err) {
console.error("ecdh error.");
return;
......@@ -2119,60 +2082,48 @@ function ecdhCallback() {
3. 通过接口`digest`,返回摘要计算结果。
4. 获取当前摘要算法名与摘要计算长度。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
// Convert strings in plaintext into byte streams.
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 以Promise方式完成摘要
function doMdByPromise() {
let mdAlgName = "SHA256"; // 摘要算法名
let message = "mdTestMessgae"; // 待摘要数据
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
let mdAlgName = "SHA256"; // Digest algorithm name.
let message = "mdTestMessgae"; // Data to be digested.
let md = cryptoFramework.createMd(mdAlgName);
;
console.info("[Promise]: Md algName is: " + md.algName);
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
// If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter.
let promiseMdUpdate = md.update({ data: stringToUint8Array(message) });
promiseMdUpdate.then(() => {
// 通过digest,返回摘要结果
// Call digest() to return the result.
let PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(digestOutput => {
mdOutput = digestOutput;
let mdOutput = digestOutput;
console.info("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Promise]: MD len: " + mdLen);
}).catch(error => {
}).catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
// 以Callback方式完成摘要
function doMdByCallback() {
let mdAlgName = "SHA256"; // 摘要算法名
let message = "mdTestMessgae"; // 待摘要数据
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
let mdAlgName = "SHA256"; // Digest algorithm name.
let message = "mdTestMessgae"; // Data to be digested.
let md = cryptoFramework.createMd(mdAlgName);
console.info("[Callback]: Md algName is: " + md.algName);
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
// If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter.
md.update({ data: stringToUint8Array(message) }, (err,) => {
if (err) {
console.error("[Callback]: err: " + err.code);
......@@ -2181,7 +2132,7 @@ function doMdByCallback() {
if (err1) {
console.error("[Callback]: err: " + err1.code);
} else {
mdOutput = digestOutput;
let mdOutput = digestOutput;
console.info("[Callback]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Callback]: MD len: " + mdLen);
......@@ -2198,59 +2149,53 @@ function doMdByCallback() {
3. 通过接口`digest`,返回摘要计算结果。
4. 获取当前摘要算法名与摘要计算长度。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 使用Promise方式,完成分段摘要
async function doLoopMdPromise() {
let mdAlgName = "SHA256"; // 摘要算法名
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
let mdAlgName = "SHA256"; // Digest algorithm name.
let md = cryptoFramework.createMd(mdAlgName);
;
console.info("[Promise]: Md algName is: " + md.algName);
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设信息总共43字节
let messageArr = [];
let updateLength = 20; // 假设每20字节分段update一次,实际并无要求
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes.
let messageArr: number[] = [];
let updateLength = 20; // For example, pass in 20 bytes in each update().
for (let i = 0; i <= messageText.length; i++) {
if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob = { data: message };
// 使用await处理for循环里的update
let messageBlob: cryptoFramework.DataBlob = { data: message };
// Use await to process the update() in the for() loop.
try {
await md.update(messageBlob); // 分段update
await md.update(messageBlob); // Use update() to process data by segment.
} catch (error) {
console.error("await update error code: " + error.code + ", message is: " + error.message);
return;
}
messageArr = [];
}
// 按分割长度,填充messageArr
// Pad messageArr based on the segment length.
if (i < messageText.length) {
messageArr.push(messageText.charCodeAt(i));
}
}
let PromiseMdDigest = md.digest();
PromiseMdDigest.then(digestOutput => {
mdOutput = digestOutput;
let mdOutput = digestOutput;
console.info("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Promise]: MD len: " + mdLen);
}).catch(error => {
}).catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
......@@ -2290,86 +2235,77 @@ Mac(message authentication code)可以对消息进行完整性校验,通过使
4. 通过接口`doFinal`,返回Mac计算结果。
5. 获取当前摘要算法名与Mac计算长度。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
// 以Promise方式完成HMAC
// Generate an HMAC in promise mode.
function doHmacByPromise() {
let macAlgName = "SHA256"; // 摘要算法名
let message = "hmacTestMessgae"; // 待hmac数据
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(macAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
let macAlgName = "SHA256"; // Digest algorithm name.
let message = "hmacTestMessgae"; // Data used to generate an HMAC.
let mac = cryptoFramework.createMac(macAlgName);
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
let KeyBlob: cryptoFramework.DataBlob = {
// 128-bit key
data: stringToUint8Array("12345678abcdefgh")
}
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
// Convert the binary data into a key.
let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
let promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
let promiseMacUpdate = mac.update({ data: stringToUint8Array(message) });
return promiseMacUpdate;
}).then(() => {
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(output => {
macOutput = output;
console.info("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.info("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
})
.then(() => {
// If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter.
let promiseMacUpdate = mac.update({ data: stringToUint8Array(message) });
return promiseMacUpdate;
})
.then(() => {
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
})
.then(output => {
let macOutput = output;
console.info("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.info("[Promise]: MAC len: " + macLen);
})
.catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
// 以Callback方式完成HMAC
// Generate an HMAC in callback mode.
function doHmacByCallback() {
let macAlgName = "SHA256"; // 摘要算法名
let message = "hmacTestMessgae"; // 待hmac数据
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(macAlgName);
} 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);
}
let macAlgName = "SHA256"; // Digest algorithm name.
let message = "hmacTestMessgae"; // Data used to generate an HMAC.
let mac = cryptoFramework.createMac(macAlgName);
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
let KeyBlob: cryptoFramework.DataBlob = {
// 128-bit key
data: stringToUint8Array("12345678abcdefgh")
}
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
// Convert the binary data into a key.
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
mac.init(symKey, (err1, ) => {
mac.init(symKey, (err1,) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
}
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
mac.update({ data: stringToUint8Array(message) }, (err2, ) => {
// If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter.
mac.update({ data: stringToUint8Array(message) }, (err2,) => {
if (err2) {
console.error("[Callback]: err: " + err2.code);
}
......@@ -2377,7 +2313,7 @@ function doHmacByCallback() {
if (err3) {
console.error("[Callback]: err: " + err3.code);
} else {
macOutput = output;
let macOutput = output;
console.error("[Callback]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.error("[Callback]: MAC len: " + macLen);
......@@ -2399,73 +2335,69 @@ function doHmacByCallback() {
4. 通过接口`doFinal`,返回Mac计算结果。
5. 获取当前摘要算法名与Mac计算长度。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
let arr = [];
function stringToUint8Array(str: string) {
let arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
return new Uint8Array(arr);
return arr;
}
function doLoopHmacPromise() {
let macAlgName = "SHA256"; // 摘要算法名
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(macAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
let macAlgName = "SHA256"; // Digest algorithm name.
let mac = cryptoFramework.createMac(macAlgName);
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
data : stringToUint8Array("12345678abcdefgh")
let KeyBlob: cryptoFramework.DataBlob = {
// 128-bit key
data: stringToUint8Array("12345678abcdefgh")
}
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设信息总共43字节
let updateLength = 20; // 假设每20字节分段update一次,实际并无要求
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes.
let updateLength = 20; // For example, pass in 20 bytes in each update().
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
// Convert the binary data into a key.
let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
promiseConvertKey.then((symKey: cryptoFramework.SymKey): Promise<void> => {
let promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(async () => {
let promiseMacUpdate;
let messageArr = [];
for (let i = 0; i <= messageText.length; i++) {
if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob = { data: message };
// 使用await处理for循环里的update
try {
promiseMacUpdate = await mac.update(messageBlob); // 分段update
} catch (error) {
console.error("await update error code: " + error.code + ", message is: " + error.message);
return;
})
.then(async () => {
let messageArr: number[] = [];
for (let i = 0; i <= messageText.length; i++) {
if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob: cryptoFramework.DataBlob = { data: message };
// Use await to process the update() in the for() loop.
try {
await mac.update(messageBlob); // Invoke update() multiple times.
} catch (error) {
console.error("await update error code: " + error.code + ", message is: " + error.message);
return;
}
messageArr = [];
}
// Pad messageArr based on the segment length.
if (i < messageText.length) {
messageArr.push(messageText.charCodeAt(i));
}
messageArr = [];
}
// 按分割长度,填充messageArr
if (i < messageText.length) {
messageArr.push(messageText.charCodeAt(i));
}
}
return promiseMacUpdate;
}).then(() => {
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(output => {
macOutput = output;
console.log("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.log("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
return;
})
.then(() => {
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
})
.then(output => {
let macOutput = output;
console.log("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.log("[Promise]: MAC len: " + macLen);
})
.catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
```
......@@ -2496,18 +2428,14 @@ function doLoopHmacPromise() {
2. 接受输入长度,通过接口`generateRandom`,生成指定长度的随机数。
3. 接受DataBlob数据,通过接口`setSeed`,为随机数生成池设置种子。
```js
```ts
import cryptoFramework from "@ohos.security.cryptoFramework"
// 通过Promise方式生成随机数
// Generate a random number in promise mode.
function doRandByPromise() {
let rand;
let len = 4; // 生成长度4字节的随机数
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
let rand = cryptoFramework.createRandom();
;
let len = 4; // Generate a 4-byte random number.
let promiseGenerateRand = rand.generateRandom(len);
promiseGenerateRand.then(randData => {
console.info("[Promise]: rand result: " + randData.data);
......@@ -2516,20 +2444,16 @@ function doRandByPromise() {
} catch (error) {
console.error("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message);
}
}).catch(error => {
}).catch((error: BusinessError) => {
console.error("[Promise]: error: " + error.message);
});
}
// 通过Callback方式生成随机数
// Generate a random number in callback mode.
function doRandByCallback() {
let rand;
let len = 4; // 生成长度4字节的随机数
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
let rand = cryptoFramework.createRandom();
;
let len = 4; // Generate a 4-byte random number.
rand.generateRandom(len, (err, randData) => {
if (err) {
console.error("[Callback]: err: " + err.code);
......@@ -2544,16 +2468,11 @@ function doRandByCallback() {
});
}
// 通过同步接口生成随机数
// Generate a random number synchronously.
function doRandBySync() {
let rand;
let len = 24; // 生成长度24字节的随机数
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Sync]: error code: " + error.code + ", message is: " + error.message);
}
let rand = cryptoFramework.createRandom();
;
let len = 24; // Generate a 24-byte random number.
try {
let randData = rand.generateRandomSync(len);
if (randData != null) {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册