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. Use [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. Use [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'AES128|CCM'** to create a **Cipher** instance. The key type is AES128, and the block cipher mode is CCM.
15
163. Use [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. Use [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. Use [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, extract the last 12 bytes from the encrypted data as the authentication information for initializing the **Cipher** instance in decryption. In the example, **authTag** is of 12 bytes.
32
33
34**Decryption**
35
36
371. Use [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.
38
392. Use [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data.
40
41
42- Example (using asynchronous APIs):
43
44  ```ts
45  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
46  import { buffer } from '@kit.ArkTS';
47
48  function genCcmParamsSpec() {
49    let rand: cryptoFramework.Random = cryptoFramework.createRandom();
50    let ivBlob: cryptoFramework.DataBlob = rand.generateRandomSync(7);
51    let aadBlob: cryptoFramework.DataBlob = rand.generateRandomSync(8);
52    let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes
53    let dataTag = new Uint8Array(arr);
54    let tagBlob: cryptoFramework.DataBlob = {
55      data: dataTag
56    };
57    // Obtain the CCM authTag from the Cipher.doFinal result in encryption and fill it in the params parameter of Cipher.init in decryption.
58    let ccmParamsSpec: cryptoFramework.CcmParamsSpec = {
59      iv: ivBlob,
60      aad: aadBlob,
61      authTag: tagBlob,
62      algName: "CcmParamsSpec"
63    };
64    return ccmParamsSpec;
65  }
66  let ccmParams = genCcmParamsSpec();
67
68  // Encrypt the message.
69  async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
70    let cipher = cryptoFramework.createCipher('AES128|CCM');
71    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, ccmParams);
72    let encryptUpdate = await cipher.update(plainText);
73    // In CCM mode, pass in null in Cipher.doFinal in encryption. Obtain the tag data and fill it in the ccmParams object.
74    ccmParams.authTag = await cipher.doFinal(null);
75    return encryptUpdate;
76  }
77  // Decrypt the message.
78  async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
79    let decoder = cryptoFramework.createCipher('AES128|CCM');
80    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, ccmParams);
81    let decryptUpdate = await decoder.doFinal(cipherText);
82    return decryptUpdate;
83  }
84  async function genSymKeyByData(symKeyData: Uint8Array) {
85    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
86    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
87    let symKey = await aesGenerator.convertKey(symKeyBlob);
88    console.info('convertKey success');
89    return symKey;
90  }
91  async function main() {
92    let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
93    let symKey = await genSymKeyByData(keyData);
94    let message = "This is a test";
95    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
96    let encryptText = await encryptMessagePromise(symKey, plainText);
97    let decryptText = await decryptMessagePromise(symKey, encryptText);
98    if (plainText.data.toString() === decryptText.data.toString()) {
99      console.info('decrypt ok');
100      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
101    } else {
102      console.error('decrypt failed');
103    }
104  }
105  ```
106
107- Example (using synchronous APIs):
108
109  ```ts
110  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
111  import { buffer } from '@kit.ArkTS';
112
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