1# Encryption and Decryption (ArkTS)
2
3This topic walks you through on how to perform encryption and decryption using AES128, RSA2048, and SM2. For details about the scenarios and supported algorithms, see [Supported Algorithms](huks-encryption-decryption-overview.md#supported-algorithms).
4
5## How to Develop
6
7**Key Generation**
8
91. Set the key alias.
10
112. Initialize the key property set.
12
133. Use [generateKeyItem](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. For details, see [Key Generation](huks-key-generation-overview.md).
14
15Alternatively, you can [import a key](huks-key-import-overview.md).
16
17**Encryption**
18
191. Obtain the key alias.
20
212. Obtain the data to be encrypted.
22
233. Obtain the [algorithm parameters](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksparam) for encryption.
24
25   The parameters to be configured vary with the algorithm used.
26   - If the AES algorithm, CBC block mode, and PKCS7 padding mode are used for encryption, the **IV** parameter must be set. For details, see [AES/CBC/PKCS7](#aescbcpkcs7).
27   - If the AES algorithm and GCM block mode are used for encryption, the **NONCE** parameter is mandatory and **AAD** is optional. For details, see [AES/GCM/NoPadding](#aesgcmnopadding).
28   - If the RSA algorithm is used for encryption, you need to select the corresponding block mode, padding mode, and digest algorithm. For details, see [RSA/ECB/PKCS1_V1_5](#rsaecbpkcs1_v1_5) and [RSA/ECB/OAEP/SHA256](#rsaecboaepsha256).
29   - If the SM2 algorithm is used for encryption, the digest algorithm must be SM3. For details, see [SM2](#sm2).
30
31   For details about the specifications, see [Encryption and Decryption Overview and Algorithm Specifications](huks-encryption-decryption-overview.md).
32
334. Use [initSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksinitsession9) to initialize a key session. The session handle is returned after the initialization.
34
355. Use [finishSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksfinishsession9) with the session handle to obtain the ciphertext.
36
37**Decryption**
38
391. Obtain the key alias.
40
412. Obtain the ciphertext to be decrypted.
42
433. Obtain the [algorithm parameters](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksparam) for decryption.
44
45   The parameters to be configured vary with the algorithm used.
46   - If the AES algorithm and GCM block mode are used for encryption, **NONCE** and **AEAD** are mandatory and **AAD** is optional. For details, see [AES/GCM/NoPadding](#aesgcmnopadding).
47   - The requirements for the parameters in the other development cases are the same as those in the encryption.
48
49   For details about the specifications, see [Encryption and Decryption Overview and Algorithm Specifications](huks-encryption-decryption-overview.md).
50
514. Use [initSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksinitsession9) to initialize a key session. The session handle is returned after the initialization.
52
535. Use [finishSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksfinishsession9) to obtain the data decrypted.
54
55**Key Deletion**
56
57Use [deleteKeyItem](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksdeletekeyitem9) to delete the key that is not required. For details, see [Deleting a Key](huks-delete-key-arkts.md).
58
59## Development Cases
60
61### AES/CBC/PKCS7
62
63```ts
64/*
65 * The following uses AES/CBC/PKCS7 with promise-based APIs.
66 */
67import { huks } from '@kit.UniversalKeystoreKit';
68
69let aesKeyAlias = 'test_aesKeyAlias';
70let handle: number;
71let plainText = '123456';
72let IV = '001122334455';
73let cipherData: Uint8Array;
74
75function StringToUint8Array(str: String) {
76  let arr: number[] = new Array();
77  for (let i = 0, j = str.length; i < j; ++i) {
78    arr.push(str.charCodeAt(i));
79  }
80  return new Uint8Array(arr);
81}
82
83function Uint8ArrayToString(fileData: Uint8Array) {
84  let dataString = '';
85  for (let i = 0; i < fileData.length; i++) {
86    dataString += String.fromCharCode(fileData[i]);
87  }
88  return dataString;
89}
90
91function GetAesGenerateProperties() {
92  let properties: Array<huks.HuksParam> = [{
93    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
94    value: huks.HuksKeyAlg.HUKS_ALG_AES
95  }, {
96    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
97    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
98  }, {
99    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
100    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
101    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
102  }];
103  return properties;
104}
105
106function GetAesEncryptProperties() {
107  let properties: Array<huks.HuksParam> = [{
108    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
109    value: huks.HuksKeyAlg.HUKS_ALG_AES
110  }, {
111    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
112    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
113  }, {
114    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
115    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
116  }, {
117    tag: huks.HuksTag.HUKS_TAG_PADDING,
118    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
119  }, {
120    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
121    value: huks.HuksCipherMode.HUKS_MODE_CBC
122  }, {
123    tag: huks.HuksTag.HUKS_TAG_IV,
124    value: StringToUint8Array(IV)
125  }];
126  return properties;
127}
128
129function GetAesDecryptProperties() {
130  let properties: Array<huks.HuksParam> = [{
131    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
132    value: huks.HuksKeyAlg.HUKS_ALG_AES
133  }, {
134    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
135    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
136  }, {
137    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
138    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
139  }, {
140    tag: huks.HuksTag.HUKS_TAG_PADDING,
141    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
142  }, {
143    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
144    value: huks.HuksCipherMode.HUKS_MODE_CBC
145  }, {
146    tag: huks.HuksTag.HUKS_TAG_IV,
147    value: StringToUint8Array(IV)
148  }];
149  return properties;
150}
151
152async function GenerateAesKey() {
153  /*
154  * Simulate the key generation scenario.
155  * 1. Set the key alias.
156  */
157  /*
158  * 2. Obtain the parameters for key generation.
159  */
160  let genProperties = GetAesGenerateProperties();
161  let options: huks.HuksOptions = {
162    properties: genProperties
163  }
164  /*
165  * 3. Call generateKeyItem.
166  */
167  await huks.generateKeyItem(aesKeyAlias, options)
168    .then((data) => {
169      console.info(`promise: generate AES Key success, data = ${JSON.stringify(data)}`);
170    }).catch((error: Error) => {
171      console.error(`promise: generate AES Key failed, ${JSON.stringify(error)}`);
172    })
173}
174
175async function EncryptData() {
176  /*
177  * Simulate the encryption scenario.
178  * 1. Obtain the key alias.
179  */
180  /*
181  * 2. Obtain the data to be encrypted.
182  */
183  /*
184  * 3. Obtain the algorithm parameters for encryption.
185  */
186  let encryptProperties = GetAesEncryptProperties();
187  let options: huks.HuksOptions = {
188    properties: encryptProperties,
189    inData: StringToUint8Array(plainText)
190  }
191  /*
192  * 4. Call initSession to obtain a session handle.
193  */
194  await huks.initSession(aesKeyAlias, options)
195    .then((data) => {
196      handle = data.handle;
197    }).catch((error: Error) => {
198      console.error(`promise: init EncryptData failed, ${JSON.stringify(error)}`);
199    })
200  /*
201  * 5. Call finishSession to obtain the ciphertext.
202  */
203  await huks.finishSession(handle, options)
204    .then((data) => {
205      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
206      cipherData = data.outData as Uint8Array;
207    }).catch((error: Error) => {
208      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
209    })
210}
211
212async function DecryptData() {
213  /*
214  * Simulate the decryption scenario.
215  * 1. Obtain the key alias.
216  */
217  /*
218  * 2. Obtain the ciphertext to be decrypted.
219  */
220  /*
221  * 3. Obtain the algorithm parameters for decryption.
222  */
223  let decryptOptions = GetAesDecryptProperties()
224  let options: huks.HuksOptions = {
225    properties: decryptOptions,
226    inData: cipherData
227  }
228  /*
229  * 4. Call initSession to obtain a session handle.
230  */
231  await huks.initSession(aesKeyAlias, options)
232    .then((data) => {
233      handle = data.handle;
234    }).catch((error: Error) => {
235      console.error(`promise: init DecryptData failed, ${JSON.stringify(error)}`);
236    })
237  /*
238  * 5. Call finishSession to obtain the decrypted data.
239  */
240  await huks.finishSession(handle, options)
241    .then((data) => {
242      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
243    }).catch((error: Error) => {
244      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
245    })
246}
247
248async function DeleteKey() {
249  /*
250  * Simulate the key deletion scenario.
251  * 1. Obtain the key alias.
252  */
253  let emptyOptions: huks.HuksOptions = {
254    properties: []
255  }
256  /*
257  * 2. Call deleteKeyItem to delete the key.
258  */
259  await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
260    .then((data) => {
261      console.info(`promise: delete data success`);
262    }).catch((error: Error) => {
263      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
264    })
265}
266```
267
268### AES/GCM/NoPadding
269
270```ts
271/*
272 * The following uses AES/GCM/NoPadding with promise-based APIs.
273 */
274import { huks } from '@kit.UniversalKeystoreKit';
275
276let aesKeyAlias = 'test_aesKeyAlias';
277let handle: number;
278let plainText = '123456';
279let cipherData: Uint8Array;
280let AAD = '1234567890123456';
281let NONCE = '001122334455';
282
283function StringToUint8Array(str: String) {
284  let arr: number[] = new Array();
285  for (let i = 0, j = str.length; i < j; ++i) {
286    arr.push(str.charCodeAt(i));
287  }
288  return new Uint8Array(arr);
289}
290
291function Uint8ArrayToString(fileData: Uint8Array) {
292  let dataString = '';
293  for (let i = 0; i < fileData.length; i++) {
294    dataString += String.fromCharCode(fileData[i]);
295  }
296  return dataString;
297}
298
299function GetAesGenerateProperties() {
300  let properties: Array<huks.HuksParam> = [{
301    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
302    value: huks.HuksKeyAlg.HUKS_ALG_AES
303  }, {
304    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
305    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
306  }, {
307    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
308    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
309    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
310  }];
311  return properties;
312}
313
314function GetAesGcmEncryptProperties() {
315  let properties: Array<huks.HuksParam> = [{
316    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
317    value: huks.HuksKeyAlg.HUKS_ALG_AES
318  }, {
319    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
320    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
321  }, {
322    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
323    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
324  }, {
325    tag: huks.HuksTag.HUKS_TAG_PADDING,
326    value: huks.HuksKeyPadding.HUKS_PADDING_NONE
327  }, {
328    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
329    value: huks.HuksCipherMode.HUKS_MODE_GCM
330  }, {
331    tag: huks.HuksTag.HUKS_TAG_NONCE,
332    value: StringToUint8Array(NONCE)
333  }, {
334    tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
335    value: StringToUint8Array(AAD)
336  }];
337  return properties;
338}
339
340function GetAesGcmDecryptProperties(cipherData:Uint8Array) {
341  let properties: Array<huks.HuksParam> = [
342    {
343      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
344      value: huks.HuksKeyAlg.HUKS_ALG_AES
345    }, {
346    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
347    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
348  }, {
349    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
350    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
351  }, {
352    tag: huks.HuksTag.HUKS_TAG_PADDING,
353    value: huks.HuksKeyPadding.HUKS_PADDING_NONE
354  }, {
355    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
356    value: huks.HuksCipherMode.HUKS_MODE_GCM
357  }, {
358    tag: huks.HuksTag.HUKS_TAG_NONCE,
359    value: StringToUint8Array(NONCE)
360  }, {
361    tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
362    value: StringToUint8Array(AAD)
363  }, {
364    tag: huks.HuksTag.HUKS_TAG_AE_TAG,
365    value: cipherData.slice(cipherData.length-16)
366  }];
367  return properties;
368}
369
370async function GenerateAesKey() {
371  /*
372  * Simulate the key generation scenario.
373  * 1. Set the key alias.
374  */
375  /*
376  * 2. Obtain the parameters for key generation.
377  */
378  let genProperties = GetAesGenerateProperties();
379  let options: huks.HuksOptions = {
380    properties: genProperties
381  }
382  /*
383  * 3. Call generateKeyItem.
384  */
385  await huks.generateKeyItem(aesKeyAlias, options)
386    .then((data) => {
387      console.info(`promise: generate AES Key success, data = ${JSON.stringify(data)}`);
388    }).catch((error: Error) => {
389      console.error(`promise: generate AES Key failed, ${JSON.stringify(error)}`);
390    })
391}
392
393async function EncryptData() {
394  /*
395  * Simulate the encryption scenario.
396  * 1. Obtain the key alias.
397  */
398  /*
399  * 2. Obtain the data to be encrypted.
400  */
401  /*
402  * 3. Obtain the algorithm parameters for encryption.
403  */
404  let encryptProperties = GetAesGcmEncryptProperties();
405  let options: huks.HuksOptions = {
406    properties: encryptProperties,
407    inData: StringToUint8Array(plainText)
408  }
409  /*
410  * 4. Call initSession to obtain a session handle.
411  */
412  await huks.initSession(aesKeyAlias, options)
413    .then((data) => {
414      handle = data.handle;
415    }).catch((error: Error) => {
416      console.error(`promise: init EncryptDataGcm failed, ${JSON.stringify(error)}`);
417    })
418  /*
419  * 5. Call finishSession to obtain the ciphertext.
420  */
421  await huks.finishSession(handle, options)
422    .then((data) => {
423      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
424      cipherData = data.outData as Uint8Array;
425    }).catch((error: Error) => {
426      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
427    })
428}
429
430async function DecryptData() {
431  /*
432  * Simulate the decryption scenario.
433  * 1. Obtain the key alias.
434  */
435  /*
436  * 2. Obtain the ciphertext to be decrypted.
437  */
438  /*
439  * 3. Obtain the algorithm parameters for decryption.
440  */
441  let decryptOptions = GetAesGcmDecryptProperties(cipherData)
442  let options: huks.HuksOptions = {
443    properties: decryptOptions,
444    inData: cipherData.slice(0, cipherData.length-16)
445  }
446  /*
447  * 4. Call initSession to obtain a session handle.
448  */
449  await huks.initSession(aesKeyAlias, options)
450    .then((data) => {
451      handle = data.handle;
452    }).catch((error: Error) => {
453      console.error(`promise: init DecryptDataGcm failed, ${JSON.stringify(error)}`);
454    })
455  /*
456  * 5. Call finishSession to obtain the decrypted data.
457  */
458  await huks.finishSession(handle, options)
459    .then((data) => {
460      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
461    }).catch((error: Error) => {
462      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
463    })
464}
465
466async function DeleteKey() {
467  /*
468  * Simulate the key deletion scenario.
469  * 1. Obtain the key alias.
470  */
471  let emptyOptions: huks.HuksOptions = {
472    properties: []
473  }
474  /*
475  * 2. Call deleteKeyItem to delete the key.
476  */
477  await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
478    .then((data) => {
479      console.info(`promise: delete data success`);
480    }).catch((error: Error) => {
481      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
482    })
483}
484```
485
486### RSA/ECB/PKCS1_V1_5
487
488```
489/*
490 * The following uses RSA/ECB/PKCS1_V1_5 with promise-based APIs.
491 */
492import { huks } from '@kit.UniversalKeystoreKit';
493
494let rsaKeyAlias = 'test_rsaKeyAlias';
495let handle: number;
496let plainText = '123456';
497let cipherData: Uint8Array;
498
499function StringToUint8Array(str: String) {
500  let arr: number[] = new Array();
501  for (let i = 0, j = str.length; i < j; ++i) {
502    arr.push(str.charCodeAt(i));
503  }
504  return new Uint8Array(arr);
505}
506
507function Uint8ArrayToString(fileData: Uint8Array) {
508  let dataString = '';
509  for (let i = 0; i < fileData.length; i++) {
510    dataString += String.fromCharCode(fileData[i]);
511  }
512  return dataString;
513}
514
515function GetRsaGenerateProperties() {
516  let properties: Array<huks.HuksParam> = [{
517    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
518    value: huks.HuksKeyAlg.HUKS_ALG_RSA
519  }, {
520    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
521    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
522  }, {
523    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
524    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
525    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
526  }];
527  return properties;
528}
529
530function GetRsaEncryptProperties() {
531  let properties: Array<huks.HuksParam> = [{
532    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
533    value: huks.HuksKeyAlg.HUKS_ALG_RSA
534  }, {
535    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
536    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
537  }, {
538    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
539    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
540  }, {
541    tag: huks.HuksTag.HUKS_TAG_PADDING,
542    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
543  }, {
544    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
545    value: huks.HuksCipherMode.HUKS_MODE_ECB
546  }, {
547    tag: huks.HuksTag.HUKS_TAG_DIGEST,
548    value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
549  }];
550  return properties;
551}
552
553function GetRsaDecryptProperties() {
554  let properties: Array<huks.HuksParam> = [{
555    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
556    value: huks.HuksKeyAlg.HUKS_ALG_RSA
557  }, {
558    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
559    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
560  }, {
561    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
562    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
563  }, {
564    tag: huks.HuksTag.HUKS_TAG_PADDING,
565    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
566  }, {
567    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
568    value: huks.HuksCipherMode.HUKS_MODE_ECB
569  }, {
570    tag: huks.HuksTag.HUKS_TAG_DIGEST,
571    value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
572  }];
573  return properties;
574}
575
576async function GenerateRsaKey() {
577  /*
578  * Simulate the key generation scenario.
579  * 1. Set the key alias.
580  */
581  /*
582  * 2. Obtain the parameters for key generation.
583  */
584  let genProperties = GetRsaGenerateProperties();
585  let options: huks.HuksOptions = {
586    properties: genProperties
587  }
588  /*
589  * 3. Call generateKeyItem.
590  */
591  await huks.generateKeyItem(rsaKeyAlias, options)
592    .then((data) => {
593      console.info(`promise: generate RSA Key success, data = ${JSON.stringify(data)}`);
594    }).catch((error: Error) => {
595      console.error(`promise: generate RSA Key failed, ${JSON.stringify(error)}`);
596    })
597}
598
599async function EncryptData() {
600  /*
601  * Simulate the encryption scenario.
602  * 1. Obtain the key alias.
603  */
604  /*
605  * 2. Obtain the data to be encrypted.
606  */
607  /*
608  * 3. Obtain the algorithm parameters for encryption.
609  */
610  let encryptProperties = GetRsaEncryptProperties();
611  let options: huks.HuksOptions = {
612    properties: encryptProperties,
613    inData: StringToUint8Array(plainText)
614  }
615  /*
616  * 4. Call initSession to obtain a session handle.
617  */
618  await huks.initSession(rsaKeyAlias, options)
619    .then((data) => {
620      handle = data.handle;
621    }).catch((error: Error) => {
622      console.error(`promise: init EncryptDataRsa failed, ${JSON.stringify(error)}`);
623    })
624  /*
625  * 5. Call finishSession to obtain the ciphertext.
626  */
627  await huks.finishSession(handle, options)
628    .then((data) => {
629      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
630      cipherData = data.outData as Uint8Array;
631    }).catch((error: Error) => {
632      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
633    })
634}
635
636async function DecryptData() {
637  /*
638  * Simulate the decryption scenario.
639  * 1. Obtain the key alias.
640  */
641  /*
642  * 2. Obtain the ciphertext to be decrypted.
643  */
644  /*
645  * 3. Obtain the algorithm parameters for decryption.
646  */
647  let decryptOptions = GetRsaDecryptProperties()
648  let options: huks.HuksOptions = {
649    properties: decryptOptions,
650    inData: cipherData
651  }
652  /*
653  * 4. Call initSession to obtain a session handle.
654  */
655  await huks.initSession(rsaKeyAlias, options)
656    .then((data) => {
657      handle = data.handle;
658    }).catch((error: Error) => {
659      console.error(`promise: init DecryptDataRsa failed, ${JSON.stringify(error)}`);
660    })
661  /*
662  * 5. Call finishSession to obtain the decrypted data.
663  */
664  await huks.finishSession(handle, options)
665    .then((data) => {
666      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
667    }).catch((error: Error) => {
668      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
669    })
670}
671
672async function DeleteKey() {
673  /*
674  * Simulate the key deletion scenario.
675  * 1. Obtain the key alias.
676  */
677  let emptyOptions: huks.HuksOptions = {
678    properties: []
679  }
680  /*
681  * 2. Call deleteKeyItem to delete the key.
682  */
683  await huks.deleteKeyItem(rsaKeyAlias, emptyOptions)
684    .then((data) => {
685      console.info(`promise: delete data success`);
686    }).catch((error: Error) => {
687      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
688    })
689}
690```
691
692### RSA/ECB/OAEP/SHA256
693
694```
695/*
696 * The following uses RSA/ECB/OAEP/SHA256 with promise-based APIs.
697 */
698import { huks } from '@kit.UniversalKeystoreKit';
699
700let rsaKeyAlias = 'test_rsaKeyAlias';
701let handle: number;
702let plainText = '123456';
703let cipherData: Uint8Array;
704
705function StringToUint8Array(str: String) {
706  let arr: number[] = new Array();
707  for (let i = 0, j = str.length; i < j; ++i) {
708    arr.push(str.charCodeAt(i));
709  }
710  return new Uint8Array(arr);
711}
712
713function Uint8ArrayToString(fileData: Uint8Array) {
714  let dataString = '';
715  for (let i = 0; i < fileData.length; i++) {
716    dataString += String.fromCharCode(fileData[i]);
717  }
718  return dataString;
719}
720
721function GetRsaGenerateProperties() {
722  let properties: Array<huks.HuksParam> = [{
723    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
724    value: huks.HuksKeyAlg.HUKS_ALG_RSA
725  }, {
726    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
727    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
728  }, {
729    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
730    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
731    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
732  }];
733  return properties;
734}
735
736function GetRsaEncryptProperties() {
737  let properties: Array<huks.HuksParam> = [{
738    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
739    value: huks.HuksKeyAlg.HUKS_ALG_RSA
740  }, {
741    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
742    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
743  }, {
744    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
745    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
746  }, {
747    tag: huks.HuksTag.HUKS_TAG_PADDING,
748    value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
749  }, {
750    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
751    value: huks.HuksCipherMode.HUKS_MODE_ECB
752  }, {
753    tag: huks.HuksTag.HUKS_TAG_DIGEST,
754    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
755  }];
756  return properties;
757}
758
759function GetRsaDecryptProperties() {
760  let properties: Array<huks.HuksParam> = [{
761    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
762    value: huks.HuksKeyAlg.HUKS_ALG_RSA
763  }, {
764    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
765    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
766  }, {
767    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
768    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
769  }, {
770    tag: huks.HuksTag.HUKS_TAG_PADDING,
771    value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
772  }, {
773    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
774    value: huks.HuksCipherMode.HUKS_MODE_ECB
775  }, {
776    tag: huks.HuksTag.HUKS_TAG_DIGEST,
777    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
778  }];
779  return properties;
780}
781
782async function GenerateRsaKey() {
783  /*
784  * Simulate the key generation scenario.
785  * 1. Set the key alias.
786  */
787  /*
788  * 2. Obtain the parameters for key generation.
789  */
790  let genProperties = GetRsaGenerateProperties();
791  let options: huks.HuksOptions = {
792    properties: genProperties
793  }
794  /*
795  * 3. Call generateKeyItem.
796  */
797  await huks.generateKeyItem(rsaKeyAlias, options)
798    .then((data) => {
799      console.info(`promise: generate RSA Key success, data = ${JSON.stringify(data)}`);
800    }).catch((error: Error) => {
801      console.error(`promise: generate RSA Key failed, ${JSON.stringify(error)}`);
802    })
803}
804
805async function EncryptData() {
806  /*
807  * Simulate the encryption scenario.
808  * 1. Obtain the key alias.
809  */
810  /*
811  * 2. Obtain the data to be encrypted.
812  */
813  /*
814  * 3. Obtain the algorithm parameters for encryption.
815  */
816  let encryptProperties = GetRsaEncryptProperties();
817  let options: huks.HuksOptions = {
818    properties: encryptProperties,
819    inData: StringToUint8Array(plainText)
820  }
821  /*
822  * 4. Call initSession to obtain a session handle.
823  */
824  await huks.initSession(rsaKeyAlias, options)
825    .then((data) => {
826      handle = data.handle;
827    }).catch((error: Error) => {
828      console.error(`promise: init EncryptDataRsa failed, ${JSON.stringify(error)}`);
829    })
830  /*
831  * 5. Call finishSession to obtain the ciphertext.
832  */
833  await huks.finishSession(handle, options)
834    .then((data) => {
835      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
836      cipherData = data.outData as Uint8Array;
837    }).catch((error: Error) => {
838      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
839    })
840}
841
842async function DecryptData() {
843  /*
844  * Simulate the decryption scenario.
845  * 1. Obtain the key alias.
846  */
847  /*
848  * 2. Obtain the ciphertext to be decrypted.
849  */
850  /*
851  * 3. Obtain the algorithm parameters for decryption.
852  */
853  let decryptOptions = GetRsaDecryptProperties()
854  let options: huks.HuksOptions = {
855    properties: decryptOptions,
856    inData: cipherData
857  }
858  /*
859  * 4. Call initSession to obtain a session handle.
860  */
861  await huks.initSession(rsaKeyAlias, options)
862    .then((data) => {
863      handle = data.handle;
864    }).catch((error: Error) => {
865      console.error(`promise: init DecryptDataRsa failed, ${JSON.stringify(error)}`);
866    })
867  /*
868  * 5. Call finishSession to obtain the decrypted data.
869  */
870  await huks.finishSession(handle, options)
871    .then((data) => {
872      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
873    }).catch((error: Error) => {
874      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
875    })
876}
877
878async function DeleteKey() {
879  /*
880  * Simulate the key deletion scenario.
881  * 1. Obtain the key alias.
882  */
883  let emptyOptions: huks.HuksOptions = {
884    properties: []
885  }
886  /*
887  * 2. Call deleteKeyItem to delete the key.
888  */
889  await huks.deleteKeyItem(rsaKeyAlias, emptyOptions)
890    .then((data) => {
891      console.info(`promise: delete data success`);
892    }).catch((error: Error) => {
893      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
894    })
895}
896```
897
898### SM2
899
900```ts
901/*
902 * The following uses SM2 with promise-based APIs.
903 */
904import { huks } from '@kit.UniversalKeystoreKit';
905
906let sm2KeyAlias = 'test_sm2KeyAlias';
907let handle: number;
908let plainText = '123456';
909let cipherData: Uint8Array;
910
911function StringToUint8Array(str: String) {
912  let arr: number[] = new Array();
913  for (let i = 0, j = str.length; i < j; ++i) {
914    arr.push(str.charCodeAt(i));
915  }
916  return new Uint8Array(arr);
917}
918
919function Uint8ArrayToString(fileData: Uint8Array) {
920  let dataString = '';
921  for (let i = 0; i < fileData.length; i++) {
922    dataString += String.fromCharCode(fileData[i]);
923  }
924  return dataString;
925}
926
927function GetSm2GenerateProperties() {
928  let properties: Array<huks.HuksParam> = [{
929    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
930    value: huks.HuksKeyAlg.HUKS_ALG_SM2
931  }, {
932    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
933    value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
934  }, {
935    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
936    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
937    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
938  }];
939  return properties;
940}
941
942function GetSm2EncryptProperties() {
943  let properties: Array<huks.HuksParam> = [{
944    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
945    value: huks.HuksKeyAlg.HUKS_ALG_SM2
946  }, {
947    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
948    value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
949  }, {
950    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
951    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
952  }, {
953    tag: huks.HuksTag.HUKS_TAG_DIGEST,
954    value: huks.HuksKeyDigest.HUKS_DIGEST_SM3
955  }];
956  return properties;
957}
958
959function GetSm2DecryptProperties() {
960  let properties: Array<huks.HuksParam> = [{
961    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
962    value: huks.HuksKeyAlg.HUKS_ALG_SM2
963  }, {
964    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
965    value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256
966  }, {
967    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
968    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
969  }, {
970    tag: huks.HuksTag.HUKS_TAG_DIGEST,
971    value: huks.HuksKeyDigest.HUKS_DIGEST_SM3
972  }];
973  return properties;
974}
975
976async function GenerateSm2Key() {
977  /*
978  * Simulate the key generation scenario.
979  * 1. Set the key alias.
980  */
981  /*
982  * 2. Obtain the parameters for key generation.
983  */
984  let genProperties = GetSm2GenerateProperties();
985  let options: huks.HuksOptions = {
986    properties: genProperties
987  }
988  /*
989  * 3. Call generateKeyItem.
990  */
991  await huks.generateKeyItem(sm2KeyAlias, options)
992    .then((data) => {
993      console.info(`promise: generate SM2 Key success, data = ${JSON.stringify(data)}`);
994    }).catch((error: Error) => {
995      console.error(`promise: generate SM2 Key failed, ${JSON.stringify(error)}`);
996    })
997}
998
999async function EncryptDataSm2() {
1000  /*
1001  * Simulate the encryption scenario.
1002  * 1. Obtain the key alias.
1003  */
1004  /*
1005  * 2. Obtain the data to be encrypted.
1006  */
1007  /*
1008  * 3. Obtain the algorithm parameters for encryption.
1009  */
1010  let encryptProperties = GetSm2EncryptProperties();
1011  let options: huks.HuksOptions = {
1012    properties: encryptProperties,
1013    inData: StringToUint8Array(plainText)
1014  }
1015  /*
1016  * 4. Call initSession to obtain a session handle.
1017  */
1018  await huks.initSession(sm2KeyAlias, options)
1019    .then((data) => {
1020      handle = data.handle;
1021    }).catch((error: Error) => {
1022      console.error(`promise: init EncryptDataSm2 failed, ${JSON.stringify(error)}`);
1023    })
1024  /*
1025  * 5. Call finishSession to obtain the ciphertext.
1026  */
1027  await huks.finishSession(handle, options)
1028    .then((data) => {
1029      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
1030      cipherData = data.outData as Uint8Array;
1031    }).catch((error: Error) => {
1032      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
1033    })
1034}
1035
1036async function DecryptDataSm2() {
1037  /*
1038  * Simulate the decryption scenario.
1039  * 1. Obtain the key alias.
1040  */
1041  /*
1042  * 2. Obtain the ciphertext to be decrypted.
1043  */
1044  /*
1045  * 3. Obtain the algorithm parameters for decryption.
1046  */
1047  let decryptOptions = GetSm2DecryptProperties()
1048  let options: huks.HuksOptions = {
1049    properties: decryptOptions,
1050    inData: cipherData
1051  }
1052  /*
1053  * 4. Call initSession to obtain a session handle.
1054  */
1055  await huks.initSession(sm2KeyAlias, options)
1056    .then((data) => {
1057      handle = data.handle;
1058    }).catch((error: Error) => {
1059      console.error(`promise: init DecryptDataSm2 failed, ${JSON.stringify(error)}`);
1060    })
1061  /*
1062  * 5. Call finishSession to obtain the decrypted data.
1063  */
1064  await huks.finishSession(handle, options)
1065    .then((data) => {
1066      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
1067    }).catch((error: Error) => {
1068      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
1069    })
1070}
1071
1072async function DeleteKey() {
1073  /*
1074  * Simulate the key deletion scenario.
1075  * 1. Obtain the key alias.
1076  */
1077  let emptyOptions: huks.HuksOptions = {
1078    properties: []
1079  }
1080  /*
1081  * 2. Call deleteKeyItem to delete the key.
1082  */
1083  await huks.deleteKeyItem(sm2KeyAlias, emptyOptions)
1084    .then((data) => {
1085      console.info(`promise: delete data success`);
1086    }).catch((error: Error) => {
1087      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
1088    })
1089}
1090```
1091
1092<!--Del-->
1093### DES/CBC/NoPadding
1094
1095```ts
1096/*
1097 * The following uses DES/CBC/NoPadding with promise-based APIs as an example.
1098 */
1099import { huks } from '@kit.UniversalKeystoreKit';
1100
1101let desKeyAlias = 'test_desKeyAlias';
1102let handle: number;
1103let plainText = '12345678';
1104let IV = '12345678';
1105let cipherData: Uint8Array;
1106
1107function StringToUint8Array(str: String) {
1108  let arr: number[] = new Array();
1109  for (let i = 0, j = str.length; i < j; ++i) {
1110    arr.push(str.charCodeAt(i));
1111  }
1112  return new Uint8Array(arr);
1113}
1114
1115function Uint8ArrayToString(fileData: Uint8Array) {
1116  let dataString = '';
1117  for (let i = 0; i < fileData.length; i++) {
1118    dataString += String.fromCharCode(fileData[i]);
1119  }
1120  return dataString;
1121}
1122
1123function GetDesGenerateProperties() {
1124  let properties: Array<huks.HuksParam> = [{
1125    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1126    value: huks.HuksKeyAlg.HUKS_ALG_DES
1127  }, {
1128    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1129    value: huks.HuksKeySize.HUKS_DES_KEY_SIZE_64
1130  }, {
1131    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1132    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
1133    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1134  }];
1135  return properties;
1136}
1137
1138function GetDesEncryptProperties() {
1139  let properties: Array<huks.HuksParam> = [{
1140    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1141    value: huks.HuksKeyAlg.HUKS_ALG_DES
1142  }, {
1143    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1144    value: huks.HuksKeySize.HUKS_DES_KEY_SIZE_64
1145  }, {
1146    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1147    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
1148  }, {
1149    tag: huks.HuksTag.HUKS_TAG_PADDING,
1150    value: huks.HuksKeyPadding.HUKS_PADDING_NONE
1151  }, {
1152    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1153    value: huks.HuksCipherMode.HUKS_MODE_CBC
1154  }, {
1155    tag: huks.HuksTag.HUKS_TAG_IV,
1156    value: StringToUint8Array(IV)
1157  }];
1158  return properties;
1159}
1160
1161function GetDesDecryptProperties() {
1162  let properties: Array<huks.HuksParam> = [{
1163    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1164    value: huks.HuksKeyAlg.HUKS_ALG_DES
1165  }, {
1166    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1167    value: huks.HuksKeySize.HUKS_DES_KEY_SIZE_64
1168  }, {
1169    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1170    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1171  }, {
1172    tag: huks.HuksTag.HUKS_TAG_PADDING,
1173    value: huks.HuksKeyPadding.HUKS_PADDING_NONE
1174  }, {
1175    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1176    value: huks.HuksCipherMode.HUKS_MODE_CBC
1177  }, {
1178    tag: huks.HuksTag.HUKS_TAG_IV,
1179    value: StringToUint8Array(IV)
1180  }];
1181  return properties;
1182}
1183
1184async function GenerateDesKey() {
1185  /*
1186  * Simulate the key generation scenario.
1187  * 1. Set the key alias.
1188  */
1189  /*
1190  * 2. Obtain the parameters for key generation.
1191  */
1192  let genProperties = GetDesGenerateProperties();
1193  let options: huks.HuksOptions = {
1194    properties: genProperties
1195  }
1196  /*
1197  * 3. Call generateKeyItem.
1198  */
1199  await huks.generateKeyItem(desKeyAlias, options)
1200    .then((data) => {
1201      console.info(`promise: generate DES Key success, data = ${JSON.stringify(data)}`);
1202    }).catch((error: Error) => {
1203      console.error(`promise: generate DES Key failed, ${JSON.stringify(error)}`);
1204    })
1205}
1206
1207async function EncryptData() {
1208  /*
1209  * Simulate the encryption scenario.
1210  * 1. Obtain the key alias.
1211  */
1212  /*
1213  * 2. Obtain the data to be encrypted.
1214  */
1215  /*
1216  * 3. Obtain the algorithm parameters for encryption.
1217  */
1218  let encryptProperties = GetDesEncryptProperties();
1219  let options: huks.HuksOptions = {
1220    properties: encryptProperties,
1221    inData: StringToUint8Array(plainText)
1222  }
1223  /*
1224  * 4. Call initSession to obtain a session handle.
1225  */
1226  await huks.initSession(desKeyAlias, options)
1227    .then((data) => {
1228      handle = data.handle;
1229    }).catch((error: Error) => {
1230      console.error(`promise: init EncryptData failed, ${JSON.stringify(error)}`);
1231    })
1232  /*
1233  * 5. Call finishSession to obtain the ciphertext.
1234  */
1235  await huks.finishSession(handle, options)
1236    .then((data) => {
1237      console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
1238      cipherData = data.outData as Uint8Array;
1239    }).catch((error: Error) => {
1240      console.error(`promise: encrypt data failed, ${JSON.stringify(error)}`);
1241    })
1242}
1243
1244async function DecryptData() {
1245  /*
1246  * Simulate the decryption scenario.
1247  * 1. Obtain the key alias.
1248  */
1249  /*
1250  * 2. Obtain the ciphertext to be decrypted.
1251  */
1252  /*
1253  * 3. Obtain the algorithm parameters for decryption.
1254  */
1255  let decryptOptions = GetDesDecryptProperties()
1256  let options: huks.HuksOptions = {
1257    properties: decryptOptions,
1258    inData: cipherData
1259  }
1260  /*
1261  * 4. Call initSession to obtain a session handle.
1262  */
1263  await huks.initSession(desKeyAlias, options)
1264    .then((data) => {
1265      handle = data.handle;
1266    }).catch((error: Error) => {
1267      console.error(`promise: init DecryptData failed, ${JSON.stringify(error)}`);
1268    })
1269  /*
1270  * 5. Call finishSession to obtain the decrypted data.
1271  */
1272  await huks.finishSession(handle, options)
1273    .then((data) => {
1274      console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
1275    }).catch((error: Error) => {
1276      console.error(`promise: decrypt data failed, ${JSON.stringify(error)}`);
1277    })
1278}
1279
1280async function DeleteKey() {
1281  /*
1282  * Simulate the key deletion scenario.
1283  * 1. Obtain the key alias.
1284  */
1285  let emptyOptions: huks.HuksOptions = {
1286    properties: []
1287  }
1288  /*
1289  * 2. Call deleteKeyItem to delete the key.
1290  */
1291  await huks.deleteKeyItem(desKeyAlias, emptyOptions)
1292    .then((data) => {
1293      console.info(`promise: delete data success`);
1294    }).catch((error: Error) => {
1295      console.error(`promise: delete data failed, ${JSON.stringify(error)}`);
1296    })
1297}
1298```
1299<!--DelEnd-->
1300