• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Encryption and Decryption with an AES Symmetric Key (CCM Mode) (ArkTS)
2
3
4For details about the algorithm specifications, see [AES](crypto-sym-encrypt-decrypt-spec.md#aes).
5
6
7**Encryption**
8
9
101. Call [cryptoFramework.createSymKeyGenerator](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatesymkeygenerator) and [SymKeyGenerator.generateSymKey](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatesymkey-1) to generate a 128-bit AES symmetric key (**SymKey**).
11
12   In addition to the example in this topic, [AES](crypto-sym-key-generation-conversion-spec.md#aes) and [Randomly Generating a Symmetric Key](crypto-generate-sym-key-randomly.md) may help you better understand how to generate an AES symmetric key. Note that the input parameters in the reference documents may be different from those in the example below.
13
142. Call [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'AES128|CCM'** to create a **Cipher** instance for encryption. The key type is AES128, and the block cipher mode is CCM.
15
163. Call [Cipher.init](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#init-1) to initialize the **Cipher** instance. In the **Cipher.init** API, set **opMode** to **CryptoMode.ENCRYPT_MODE** (encryption), **key** to **SymKey** (the key for encryption), and **params** to **CcmParamsSpec** corresponding to the CCM mode.
17
184. Call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be encrypted (plaintext).
19
20   Currently, the amount of data to be passed in by a single **Cipher.update** is not limited. You can determine how to pass in data based on the data volume.
21
22   > **NOTE**<br>
23   > The CCM mode does not support segment-based encryption and decryption.
24
255. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the encrypted data.
26   - If data has been passed in by **Cipher.update**, pass in **null** in the **data** parameter of **Cipher.doFinal**.
27   - The output of **Cipher.doFinal** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
28
296. Obtain [CcmParamsSpec.authTag](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#ccmparamsspec) as the authentication information for decryption.
30
31    In CCM mode, **authTag** must be of 12 bytes. It is used as the authentication information during decryption. In the example, **authTag** is of 12 bytes.
32
33
34**Decryption**
35
361. Call [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'AES128|CCM'** to create a **Cipher** instance for decryption. The key type is AES128, and the block cipher mode is CCM.
37
382. Call [Cipher.init](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#init-1) to initialize the **Cipher** instance. In the **Cipher.init** API, set **opMode** to **CryptoMode.DECRYPT_MODE** (decryption), **key** to **SymKey** (the key for decryption), and **params** to **CcmParamsSpec** corresponding to the CCM mode.
39
403. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data.
41
42
43- Example (using asynchronous APIs):
44
45  ```ts
46  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
47  import { buffer } from '@kit.ArkTS';
48
49  function genCcmParamsSpec() {
50    let rand: cryptoFramework.Random = cryptoFramework.createRandom();
51    let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
52    let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
53    let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes
54    let dataTag = new Uint8Array(arr);
55    let tagBlob: cryptoFramework.DataBlob = {
56      data: dataTag
57    };
58    // Obtain the CCM authTag from the Cipher.doFinal result in encryption and fill it in the params parameter of Cipher.init in decryption.
59    let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
60      iv: ivBlob,
61      aad: aadBlob,
62      authTag: tagBlob,
63      algName: "CcmParamsSpec"
64    };
65    return ccmParamsSpec;
66  }
67  let ccmParams = genCcmParamsSpec();
68
69  // Encrypt the message.
70  async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
71    let cipher = cryptoFramework.createCipher('AES128|CCM');
72    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ccmParams);
73    let encryptUpdate = await cipher.update(plainText);
74    // In CCM mode, pass in null in Cipher.doFinal in encryption. Obtain the tag data and fill it in the ccmParams object.
75    ccmParams.authTag = await cipher.doFinal(null);
76    return encryptUpdate;
77  }
78  // Decrypt the message.
79  async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
80    let decoder = cryptoFramework.createCipher('AES128|CCM');
81    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ccmParams);
82    let decryptUpdate = await decoder.doFinal(cipherText);
83    return decryptUpdate;
84  }
85  async function genSymKeyByData(symKeyData: Uint8Array) {
86    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
87    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
88    let symKey = await aesGenerator.convertKey(symKeyBlob);
89    console.info('convertKey success');
90    return symKey;
91  }
92  async function main() {
93    let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
94    let symKey = await genSymKeyByData(keyData);
95    let message = "This is a test";
96    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
97    let encryptText = await encryptMessagePromise(symKey, plainText);
98    let decryptText = await decryptMessagePromise(symKey, encryptText);
99    if (plainText.data.toString() === decryptText.data.toString()) {
100      console.info('decrypt ok');
101      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
102    } else {
103      console.error('decrypt failed');
104    }
105  }
106  ```
107
108- Example (using synchronous APIs):
109
110  ```ts
111  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
112  import { buffer } from '@kit.ArkTS';
113
114    function genCcmParamsSpec() {
115      let rand: cryptoFramework.Random = cryptoFramework.createRandom();
116      let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
117      let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
118      let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes
119      let dataTag = new Uint8Array(arr);
120      let tagBlob: cryptoFramework.DataBlob = {
121        data: dataTag
122      };
123      // Obtain the CCM authTag from the Cipher.doFinal result in encryption and fill it in the params parameter of Cipher.init in decryption.
124      let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
125        iv: ivBlob,
126        aad: aadBlob,
127        authTag: tagBlob,
128        algName: "CcmParamsSpec"
129      };
130      return ccmParamsSpec;
131    }
132
133    let ccmParams = genCcmParamsSpec();
134
135    // Encrypt the message.
136    function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
137      let cipher = cryptoFramework.createCipher('AES128|CCM');
138      cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ccmParams);
139      let encryptUpdate = cipher.updateSync(plainText);
140      // In CCM mode, pass in null in Cipher.doFinal in encryption. Obtain the tag data and fill it in the ccmParams object.
141      ccmParams.authTag = cipher.doFinalSync(null);
142      return encryptUpdate;
143    }
144    // Decrypt the message.
145    function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
146      let decoder = cryptoFramework.createCipher('AES128|CCM');
147      decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ccmParams);
148      let decryptUpdate = decoder.doFinalSync(cipherText);
149      return decryptUpdate;
150    }
151    function genSymKeyByData(symKeyData: Uint8Array) {
152      let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
153      let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
154      let symKey = aesGenerator.convertKeySync(symKeyBlob);
155      console.info('convertKeySync success');
156      return symKey;
157    }
158    function main() {
159      let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
160      let symKey = genSymKeyByData(keyData);
161      let message = "This is a test";
162      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
163      let encryptText = encryptMessage(symKey, plainText);
164      let decryptText = decryptMessage(symKey, encryptText);
165      if (plainText.data.toString() === decryptText.data.toString()) {
166        console.info('decrypt ok');
167        console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
168      } else {
169        console.error('decrypt failed');
170      }
171    }
172  ```
173
174
175
176