1e41f4b71Sopenharmony_ci# Encryption and Decryption by Segment with an SM4 Symmetric Key (GCM Mode) (ArkTS) 2e41f4b71Sopenharmony_ci 3e41f4b71Sopenharmony_ci 4e41f4b71Sopenharmony_ciFor details about the algorithm specifications, see [SM4](crypto-sym-encrypt-decrypt-spec.md#sm4). 5e41f4b71Sopenharmony_ci 6e41f4b71Sopenharmony_ci 7e41f4b71Sopenharmony_ci**Encryption** 8e41f4b71Sopenharmony_ci 9e41f4b71Sopenharmony_ci 10e41f4b71Sopenharmony_ci1. 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 SM4 symmetric key (**SymKey**). 11e41f4b71Sopenharmony_ci 12e41f4b71Sopenharmony_ci In addition to the example in this topic, [SM4](crypto-sym-key-generation-conversion-spec.md#sm4) and [Randomly Generating a Symmetric Key](crypto-generate-sym-key-randomly.md) may help you better understand how to generate an SM4 symmetric key. Note that the input parameters in the reference documents may be different from those in the example below. 13e41f4b71Sopenharmony_ci 14e41f4b71Sopenharmony_ci2. Use [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'SM4_128|GCM|PKCS7'** to create a **Cipher** instance. The key type is **SM4_128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**. 15e41f4b71Sopenharmony_ci 16e41f4b71Sopenharmony_ci3. 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 **GcmParamsSpec** corresponding to the GCM mode. 17e41f4b71Sopenharmony_ci 18e41f4b71Sopenharmony_ci4. Set the size of the data to be passed in each time to 20 bytes, and call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) multiple times to pass in the data (plaintext) to be encrypted. 19e41f4b71Sopenharmony_ci 20e41f4b71Sopenharmony_ci - Currently, the amount of data to be passed in by a single **update()** is not limited. You can determine how to pass in data based on the data volume. 21e41f4b71Sopenharmony_ci - You are advised to check the result of each **update()**. If the result is not **null**, obtain the data and combine the data segments into complete ciphertext. The **update()** result may vary with the key specifications. 22e41f4b71Sopenharmony_ci 23e41f4b71Sopenharmony_ci If a block cipher mode (ECB or CBC) is used, data is encrypted and output based on the block size. That is, if the data of an **update()** operation matches the block size, the ciphertext is output. Otherwise, **null** is output, and the plaintext will be combined with the input data of the next **update()** to form a block. When **doFinal()** is called, the unencrypted data is padded to the block size based on the specified padding mode, and then encrypted. The **update()** API works in the same way in decryption. 24e41f4b71Sopenharmony_ci 25e41f4b71Sopenharmony_ci If a stream cipher mode (CTR or OFB) is used, the ciphertext length is usually the same as the plaintext length. 26e41f4b71Sopenharmony_ci 27e41f4b71Sopenharmony_ci5. Use [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the encrypted data. 28e41f4b71Sopenharmony_ci 29e41f4b71Sopenharmony_ci - If data has been passed in by **update()**, pass in **null** in the **data** parameter of **Cipher.doFinal**. 30e41f4b71Sopenharmony_ci - The output of **doFinal** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data. 31e41f4b71Sopenharmony_ci 32e41f4b71Sopenharmony_ci6. Obtain **GcmParamsSpec.authTag** as the authentication information for decryption. 33e41f4b71Sopenharmony_ci 34e41f4b71Sopenharmony_ci In GCM mode, extract the last 16 bytes from the encrypted data as the authentication information for initializing the **Cipher** instance in decryption. In the example, **authTag** is of 16 bytes. 35e41f4b71Sopenharmony_ci 36e41f4b71Sopenharmony_ci 37e41f4b71Sopenharmony_ci**Decryption** 38e41f4b71Sopenharmony_ci 39e41f4b71Sopenharmony_ci 40e41f4b71Sopenharmony_ci1. 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 **GcmParamsSpec** corresponding to the GCM mode. 41e41f4b71Sopenharmony_ci 42e41f4b71Sopenharmony_ci2. Set the size of the data to be passed in each time to 20 bytes, and call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) multiple times to pass in the data (ciphertext) to be decrypted. 43e41f4b71Sopenharmony_ci 44e41f4b71Sopenharmony_ci3. Use [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data. 45e41f4b71Sopenharmony_ci 46e41f4b71Sopenharmony_ci 47e41f4b71Sopenharmony_ci- Example (using asynchronous APIs): 48e41f4b71Sopenharmony_ci 49e41f4b71Sopenharmony_ci ```ts 50e41f4b71Sopenharmony_ci import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 51e41f4b71Sopenharmony_ci import { buffer } from '@kit.ArkTS'; 52e41f4b71Sopenharmony_ci function genGcmParamsSpec() { 53e41f4b71Sopenharmony_ci let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes 54e41f4b71Sopenharmony_ci let dataIv = new Uint8Array(arr); 55e41f4b71Sopenharmony_ci let ivBlob: cryptoFramework.DataBlob = { data: dataIv }; 56e41f4b71Sopenharmony_ci arr = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 bytes 57e41f4b71Sopenharmony_ci let dataAad = new Uint8Array(arr); 58e41f4b71Sopenharmony_ci let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 59e41f4b71Sopenharmony_ci arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes 60e41f4b71Sopenharmony_ci let dataTag = new Uint8Array(arr); 61e41f4b71Sopenharmony_ci let tagBlob: cryptoFramework.DataBlob = { 62e41f4b71Sopenharmony_ci data: dataTag 63e41f4b71Sopenharmony_ci }; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption. 64e41f4b71Sopenharmony_ci let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 65e41f4b71Sopenharmony_ci iv: ivBlob, 66e41f4b71Sopenharmony_ci aad: aadBlob, 67e41f4b71Sopenharmony_ci authTag: tagBlob, 68e41f4b71Sopenharmony_ci algName: "GcmParamsSpec" 69e41f4b71Sopenharmony_ci }; 70e41f4b71Sopenharmony_ci return gcmParamsSpec; 71e41f4b71Sopenharmony_ci } 72e41f4b71Sopenharmony_ci let gcmParams = genGcmParamsSpec(); 73e41f4b71Sopenharmony_ci // Encrypt the message by segment. 74e41f4b71Sopenharmony_ci async function encryptMessageUpdateBySegment(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) { 75e41f4b71Sopenharmony_ci let cipher = cryptoFramework.createCipher('SM4_128|GCM|PKCS7'); 76e41f4b71Sopenharmony_ci await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 77e41f4b71Sopenharmony_ci let updateLength = 20; // Set the length of the data to be passed in each time to 20 bytes. You can set this parameter as required. 78e41f4b71Sopenharmony_ci let cipherText = new Uint8Array(); 79e41f4b71Sopenharmony_ci for (let i = 0; i < plainText.data.length; i += updateLength) { 80e41f4b71Sopenharmony_ci let updateMessage = plainText.data.subarray(i, i + updateLength); 81e41f4b71Sopenharmony_ci let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage }; 82e41f4b71Sopenharmony_ci // Call update() multiple times to pass in data by segment. 83e41f4b71Sopenharmony_ci let updateOutput = await cipher.update(updateMessageBlob); 84e41f4b71Sopenharmony_ci // Combine the result of each update() to obtain the ciphertext. In certain cases, the doFinal() result also needs to be combined, which depends on the cipher block mode 85e41f4b71Sopenharmony_ci // and padding mode you use. In this example, the GCM mode is used, and the doFinal() result contains authTag but not ciphertext. Therefore, there is no need to combine the doFinal() result. 86e41f4b71Sopenharmony_ci let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length); 87e41f4b71Sopenharmony_ci mergeText.set(cipherText); 88e41f4b71Sopenharmony_ci mergeText.set(updateOutput.data, cipherText.length); 89e41f4b71Sopenharmony_ci cipherText = mergeText; 90e41f4b71Sopenharmony_ci } 91e41f4b71Sopenharmony_ci gcmParams.authTag = await cipher.doFinal(null); 92e41f4b71Sopenharmony_ci let cipherBlob: cryptoFramework.DataBlob = { data: cipherText }; 93e41f4b71Sopenharmony_ci return cipherBlob; 94e41f4b71Sopenharmony_ci } 95e41f4b71Sopenharmony_ci // Decrypt the message by segment. 96e41f4b71Sopenharmony_ci async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) { 97e41f4b71Sopenharmony_ci let decoder = cryptoFramework.createCipher('SM4_128|GCM|PKCS7'); 98e41f4b71Sopenharmony_ci await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams); 99e41f4b71Sopenharmony_ci let updateLength = 20; // Set the length of the data to be passed in each time to 20 bytes. You can set this parameter as required. 100e41f4b71Sopenharmony_ci let decryptText = new Uint8Array(); 101e41f4b71Sopenharmony_ci for (let i = 0; i < cipherText.data.length; i += updateLength) { 102e41f4b71Sopenharmony_ci let updateMessage = cipherText.data.subarray(i, i + updateLength); 103e41f4b71Sopenharmony_ci let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage }; 104e41f4b71Sopenharmony_ci // Call update() multiple times to pass in data by segment. 105e41f4b71Sopenharmony_ci let updateOutput = await decoder.update(updateMessageBlob); 106e41f4b71Sopenharmony_ci // Combine the update() results to obtain the plaintext. 107e41f4b71Sopenharmony_ci let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length); 108e41f4b71Sopenharmony_ci mergeText.set(decryptText); 109e41f4b71Sopenharmony_ci mergeText.set(updateOutput.data, decryptText.length); 110e41f4b71Sopenharmony_ci decryptText = mergeText; 111e41f4b71Sopenharmony_ci } 112e41f4b71Sopenharmony_ci let decryptData = await decoder.doFinal(null); 113e41f4b71Sopenharmony_ci if (decryptData == null) { 114e41f4b71Sopenharmony_ci console.info('GCM decrypt success, decryptData is null'); 115e41f4b71Sopenharmony_ci } 116e41f4b71Sopenharmony_ci let decryptBlob: cryptoFramework.DataBlob = { data: decryptText }; 117e41f4b71Sopenharmony_ci return decryptBlob; 118e41f4b71Sopenharmony_ci } 119e41f4b71Sopenharmony_ci async function genSymKeyByData(symKeyData: Uint8Array) { 120e41f4b71Sopenharmony_ci let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; 121e41f4b71Sopenharmony_ci let sm4Generator = cryptoFramework.createSymKeyGenerator('SM4_128'); 122e41f4b71Sopenharmony_ci let symKey = await sm4Generator.convertKey(symKeyBlob); 123e41f4b71Sopenharmony_ci console.info('convertKey success'); 124e41f4b71Sopenharmony_ci return symKey; 125e41f4b71Sopenharmony_ci } 126e41f4b71Sopenharmony_ci async function sm4() { 127e41f4b71Sopenharmony_ci let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); 128e41f4b71Sopenharmony_ci let symKey = await genSymKeyByData(keyData); 129e41f4b71Sopenharmony_ci let message = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // The message is of 43 bytes. After decoded in UTF-8 format, the message is also of 43 bytes. 130e41f4b71Sopenharmony_ci let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 131e41f4b71Sopenharmony_ci let encryptText = await encryptMessageUpdateBySegment(symKey, plainText); 132e41f4b71Sopenharmony_ci let decryptText = await decryptMessagePromise(symKey, encryptText); 133e41f4b71Sopenharmony_ci if (plainText.data.toString() === decryptText.data.toString()) { 134e41f4b71Sopenharmony_ci console.info('decrypt ok'); 135e41f4b71Sopenharmony_ci console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); 136e41f4b71Sopenharmony_ci } else { 137e41f4b71Sopenharmony_ci console.error('decrypt failed'); 138e41f4b71Sopenharmony_ci } 139e41f4b71Sopenharmony_ci } 140e41f4b71Sopenharmony_ci ``` 141e41f4b71Sopenharmony_ci 142e41f4b71Sopenharmony_ci- Example (using synchronous APIs): 143e41f4b71Sopenharmony_ci 144e41f4b71Sopenharmony_ci ```ts 145e41f4b71Sopenharmony_ci import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 146e41f4b71Sopenharmony_ci import { buffer } from '@kit.ArkTS'; 147e41f4b71Sopenharmony_ci 148e41f4b71Sopenharmony_ci function genGcmParamsSpec() { 149e41f4b71Sopenharmony_ci let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes 150e41f4b71Sopenharmony_ci let dataIv = new Uint8Array(arr); 151e41f4b71Sopenharmony_ci let ivBlob: cryptoFramework.DataBlob = { data: dataIv }; 152e41f4b71Sopenharmony_ci arr = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 bytes 153e41f4b71Sopenharmony_ci let dataAad = new Uint8Array(arr); 154e41f4b71Sopenharmony_ci let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 155e41f4b71Sopenharmony_ci arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes 156e41f4b71Sopenharmony_ci let dataTag = new Uint8Array(arr); 157e41f4b71Sopenharmony_ci let tagBlob: cryptoFramework.DataBlob = { 158e41f4b71Sopenharmony_ci data: dataTag 159e41f4b71Sopenharmony_ci }; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption. 160e41f4b71Sopenharmony_ci let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 161e41f4b71Sopenharmony_ci iv: ivBlob, 162e41f4b71Sopenharmony_ci aad: aadBlob, 163e41f4b71Sopenharmony_ci authTag: tagBlob, 164e41f4b71Sopenharmony_ci algName: "GcmParamsSpec" 165e41f4b71Sopenharmony_ci }; 166e41f4b71Sopenharmony_ci return gcmParamsSpec; 167e41f4b71Sopenharmony_ci } 168e41f4b71Sopenharmony_ci let gcmParams = genGcmParamsSpec(); 169e41f4b71Sopenharmony_ci // Encrypt the message by segment. 170e41f4b71Sopenharmony_ci function encryptMessageUpdateBySegment(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) { 171e41f4b71Sopenharmony_ci let cipher = cryptoFramework.createCipher('SM4_128|GCM|PKCS7'); 172e41f4b71Sopenharmony_ci cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 173e41f4b71Sopenharmony_ci let updateLength = 20; // Set the length of the data to be passed in each time to 20 bytes. You can set this parameter as required. 174e41f4b71Sopenharmony_ci let cipherText = new Uint8Array(); 175e41f4b71Sopenharmony_ci for (let i = 0; i < plainText.data.length; i += updateLength) { 176e41f4b71Sopenharmony_ci let updateMessage = plainText.data.subarray(i, i + updateLength); 177e41f4b71Sopenharmony_ci let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage }; 178e41f4b71Sopenharmony_ci // Call update() multiple times to pass in data by segment. 179e41f4b71Sopenharmony_ci let updateOutput = cipher.updateSync(updateMessageBlob); 180e41f4b71Sopenharmony_ci // Combine the result of each update() to obtain the ciphertext. In certain cases, the doFinal() result also needs to be combined, which depends on the cipher block mode 181e41f4b71Sopenharmony_ci // and padding mode you use. In this example, the GCM mode is used, and the doFinal() result contains authTag but not ciphertext. Therefore, there is no need to combine the doFinal() result. 182e41f4b71Sopenharmony_ci let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length); 183e41f4b71Sopenharmony_ci mergeText.set(cipherText); 184e41f4b71Sopenharmony_ci mergeText.set(updateOutput.data, cipherText.length); 185e41f4b71Sopenharmony_ci cipherText = mergeText; 186e41f4b71Sopenharmony_ci } 187e41f4b71Sopenharmony_ci gcmParams.authTag = cipher.doFinalSync(null); 188e41f4b71Sopenharmony_ci let cipherBlob: cryptoFramework.DataBlob = { data: cipherText }; 189e41f4b71Sopenharmony_ci return cipherBlob; 190e41f4b71Sopenharmony_ci } 191e41f4b71Sopenharmony_ci // Decrypt the message by segment. 192e41f4b71Sopenharmony_ci function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) { 193e41f4b71Sopenharmony_ci let decoder = cryptoFramework.createCipher('SM4_128|GCM|PKCS7'); 194e41f4b71Sopenharmony_ci decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams); 195e41f4b71Sopenharmony_ci let updateLength = 20; // Set the length of the data to be passed in each time to 20 bytes. You can set this parameter as required. 196e41f4b71Sopenharmony_ci let decryptText = new Uint8Array(); 197e41f4b71Sopenharmony_ci for (let i = 0; i < cipherText.data.length; i += updateLength) { 198e41f4b71Sopenharmony_ci let updateMessage = cipherText.data.subarray(i, i + updateLength); 199e41f4b71Sopenharmony_ci let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage }; 200e41f4b71Sopenharmony_ci // Call update() multiple times to pass in data by segment. 201e41f4b71Sopenharmony_ci let updateOutput = decoder.updateSync(updateMessageBlob); 202e41f4b71Sopenharmony_ci // Combine the update() results to obtain the plaintext. 203e41f4b71Sopenharmony_ci let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length); 204e41f4b71Sopenharmony_ci mergeText.set(decryptText); 205e41f4b71Sopenharmony_ci mergeText.set(updateOutput.data, decryptText.length); 206e41f4b71Sopenharmony_ci decryptText = mergeText; 207e41f4b71Sopenharmony_ci } 208e41f4b71Sopenharmony_ci let decryptData = decoder.doFinalSync(null); 209e41f4b71Sopenharmony_ci if (decryptData == null) { 210e41f4b71Sopenharmony_ci console.info('GCM decrypt success, decryptData is null'); 211e41f4b71Sopenharmony_ci } 212e41f4b71Sopenharmony_ci let decryptBlob: cryptoFramework.DataBlob = { data: decryptText }; 213e41f4b71Sopenharmony_ci return decryptBlob; 214e41f4b71Sopenharmony_ci } 215e41f4b71Sopenharmony_ci async function genSymKeyByData(symKeyData: Uint8Array) { 216e41f4b71Sopenharmony_ci let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; 217e41f4b71Sopenharmony_ci let sm4Generator = cryptoFramework.createSymKeyGenerator('SM4_128'); 218e41f4b71Sopenharmony_ci let symKey = await sm4Generator.convertKey(symKeyBlob); 219e41f4b71Sopenharmony_ci console.info('convertKey success'); 220e41f4b71Sopenharmony_ci return symKey; 221e41f4b71Sopenharmony_ci } 222e41f4b71Sopenharmony_ci async function main() { 223e41f4b71Sopenharmony_ci let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); 224e41f4b71Sopenharmony_ci let symKey = await genSymKeyByData(keyData); 225e41f4b71Sopenharmony_ci let message = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // The message is of 43 bytes. After decoded in UTF-8 format, the message is also of 43 bytes. 226e41f4b71Sopenharmony_ci let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 227e41f4b71Sopenharmony_ci let encryptText = encryptMessageUpdateBySegment(symKey, plainText); 228e41f4b71Sopenharmony_ci let decryptText = decryptMessage(symKey, encryptText); 229e41f4b71Sopenharmony_ci if (plainText.data.toString() === decryptText.data.toString()) { 230e41f4b71Sopenharmony_ci console.info('decrypt ok'); 231e41f4b71Sopenharmony_ci console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); 232e41f4b71Sopenharmony_ci } else { 233e41f4b71Sopenharmony_ci console.error('decrypt failed'); 234e41f4b71Sopenharmony_ci } 235e41f4b71Sopenharmony_ci } 236e41f4b71Sopenharmony_ci 237e41f4b71Sopenharmony_ci ``` 238