1# Encryption and Decryption with an AES Symmetric Key (GCM 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|GCM|PKCS7'** to create a **Cipher** instance for encryption. The key type is **AES128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**. 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 **GcmParamsSpec** corresponding to the GCM 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 - If a small amount of data is to be encrypted, you can use **Cipher.doFinal** immediately after **Cipher.init**. 23 - If a large amount of data is to be encrypted, you can call **Cipher.update** multiple times to pass in the data by segment. 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 [GcmParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#gcmparamsspec).authTag as the authentication information for decryption. 30 In GCM mode, **authTag** must be of 16 bytes. It is used as the authentication information during decryption. In the example, **authTag** is of 16 bytes. 31 32 33**Decryption** 34 351. Call [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'AES128|GCM|PKCS7'** to create a **Cipher** instance for decryption. The key type is **AES128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**. 36 372. 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 **GcmParamsSpec** corresponding to the GCM mode. 38 393. Call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be decrypted (ciphertext). 40 414. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data. 42 43 44- Example (using asynchronous APIs): 45 46 ```ts 47 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 48 import { buffer } from '@kit.ArkTS'; 49 50 function generateRandom(len: number) { 51 let rand = cryptoFramework.createRandom(); 52 let generateRandSync = rand.generateRandomSync(len); 53 return generateRandSync; 54 } 55 56 function genGcmParamsSpec() { 57 let ivBlob = generateRandom(12); 58 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 8 bytes 59 let dataAad = new Uint8Array(arr); // Convert the arr array to a Uint8Array. 60 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; // Create a DataBlob object. 61 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes 62 let dataTag = new Uint8Array(arr); // Convert the arr array to a Uint8Array. 63 let tagBlob: cryptoFramework.DataBlob = { 64 data: dataTag 65 }; 66 // Obtain the GCM authTag from the Cipher.doFinal result in encryption and fill it in the params parameter of Cipher.init in decryption. 67 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 68 iv: ivBlob, 69 aad: aadBlob, 70 authTag: tagBlob, 71 algName: "GcmParamsSpec" 72 }; 73 return gcmParamsSpec; 74 } 75 76 let gcmParams = genGcmParamsSpec(); 77 78 // Encrypt the message. 79 async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) { 80 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 81 await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 82 let encryptUpdate = await cipher.update(plainText); 83 // In GCM mode, pass in null in Cipher.doFinal in encryption. Obtain the tag data and fill it in the gcmParams object. 84 gcmParams.authTag = await cipher.doFinal(null); 85 return encryptUpdate; 86 } 87 // Decrypt the message. 88 async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) { 89 let decoder = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 90 await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams); 91 let decryptUpdate = await decoder.update(cipherText); 92 // In GCM mode, pass in null in Cipher.doFinal in decryption. Verify the tag data passed in Cipher.init. If the verification fails, an exception will be thrown. 93 let decryptData = await decoder.doFinal(null); 94 if (decryptData === null) { 95 console.info('GCM decrypt success, decryptData is null'); 96 } 97 return decryptUpdate; 98 } 99 async function genSymKeyByData(symKeyData: Uint8Array) { 100 let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; 101 let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 102 let symKey = await aesGenerator.convertKey(symKeyBlob); 103 console.info('convertKey success'); 104 return symKey; 105 } 106 async function main() { 107 let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); // Create a Uint8Array object. 108 let symKey = await genSymKeyByData(keyData); 109 let message = "This is a test"; 110 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; // Create a DataBlob object. 111 let encryptText = await encryptMessagePromise(symKey, plainText); 112 let decryptText = await decryptMessagePromise(symKey, encryptText); 113 if (plainText.data.toString() === decryptText.data.toString()) { 114 console.info('decrypt ok'); 115 console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); 116 } else { 117 console.error('decrypt failed'); 118 } 119 } 120 ``` 121 122- Example (using synchronous APIs): 123 124 ```ts 125 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 126 import { buffer } from '@kit.ArkTS'; 127 128 function generateRandom(len: number) { 129 let rand = cryptoFramework.createRandom(); 130 let generateRandSync = rand.generateRandomSync(len); 131 return generateRandSync; 132 } 133 134 function genGcmParamsSpec() { 135 let ivBlob = generateRandom(12); 136 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 8 bytes 137 let dataAad = new Uint8Array(arr); // Convert the arr array to a Uint8Array. 138 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; // Create a DataBlob object. 139 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes 140 let dataTag = new Uint8Array(arr); // Convert the arr array to a Uint8Array. 141 let tagBlob: cryptoFramework.DataBlob = { 142 data: dataTag 143 }; 144 // Obtain the GCM authTag from the Cipher.doFinal result in encryption and fill it in the params parameter of Cipher.init in decryption. 145 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 146 iv: ivBlob, 147 aad: aadBlob, 148 authTag: tagBlob, 149 algName: "GcmParamsSpec" 150 }; 151 return gcmParamsSpec; 152 } 153 154 let gcmParams = genGcmParamsSpec(); 155 156 // Encrypt the message. 157 function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) { 158 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 159 cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 160 let encryptUpdate = cipher.updateSync(plainText); 161 // In GCM mode, pass in null in Cipher.doFinal in encryption. Obtain the tag data and fill it in the gcmParams object. 162 gcmParams.authTag = cipher.doFinalSync(null); 163 return encryptUpdate; 164 } 165 // Decrypt the message. 166 function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) { 167 let decoder = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 168 decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams); 169 let decryptUpdate = decoder.updateSync(cipherText); 170 // In GCM mode, pass in null in Cipher.doFinal in decryption. Verify the tag data passed in Cipher.init. If the verification fails, an exception will be thrown. 171 let decryptData = decoder.doFinalSync(null); 172 if (decryptData === null) { 173 console.info('GCM decrypt success, decryptData is null'); 174 } 175 return decryptUpdate; 176 } 177 function genSymKeyByData(symKeyData: Uint8Array) { 178 let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; 179 let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 180 let symKey = aesGenerator.convertKeySync(symKeyBlob); 181 console.info('convertKeySync success'); 182 return symKey; 183 } 184 function main() { 185 let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); // Create a Uint8Array object. 186 let symKey = genSymKeyByData(keyData); 187 let message = "This is a test"; 188 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; // Create a DataBlob object. 189 let encryptText = encryptMessage(symKey, plainText); 190 let decryptText = decryptMessage(symKey, encryptText); 191 if (plainText.data.toString() === decryptText.data.toString()) { 192 console.info('decrypt ok'); 193 console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); 194 } else { 195 console.error('decrypt failed'); 196 } 197 } 198 ``` 199