• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode) (ArkTS)
2
3<!--Kit: Crypto Architecture Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @zxz--3-->
6<!--Designer: @lanming-->
7<!--Tester: @PAFT-->
8<!--Adviser: @zengyawen-->
9
10For details about the algorithm specifications, see [AES](crypto-sym-encrypt-decrypt-spec.md#aes).
11
12**Encryption**
13
141. 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**).
15
16   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.
17
182. 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**.
19
203. 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.
21
224. 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.
23
24   - 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.
25   - 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.
26
27      If a block cipher mode (ECB or CBC) is used, data is encrypted and output based on the block size. When the update operation fills a block, the ciphertext is output. If the block is not filled, the update operation outputs **null**, and the unencrypted data is concatenated with the data input next time, and then the data is output by block. When **Cipher.doFinal** is called, the unencrypted data is padded to the block size based on the specified padding mode, and then encrypted. The **Cipher.update** API works in the same way in decryption.
28
29      If a stream encryption mode (CTR and OFB) is used, the ciphertext length is equal to the plaintext length.
30
315. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the encrypted data.
32
33   - If data has been passed in by **Cipher.update**, pass in **null** in this step.
34   - Before accessing the **Cipher.doFinal** output, check whether the result is **null** to avoid exceptions.
35
366. Obtain [GcmParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#gcmparamsspec).authTag as the authentication information for decryption.
37
38   In GCM mode, the algorithm library supports only 16-byte **authTag**, which is used for authentication initialization during decryption. In the following example, **authTag** is of 16 bytes.
39
40**Decryption**
41
421. 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**.
43
442. 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.
45
463. 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.
47
484. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data.
49
50- Example (using asynchronous APIs):
51
52  ```ts
53  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
54  import { buffer } from '@kit.ArkTS';
55
56  function generateRandom(len: number) {
57    let rand = cryptoFramework.createRandom();
58    let generateRandSync = rand.generateRandomSync(len);
59    return generateRandSync;
60  }
61
62  function genGcmParamsSpec() {
63    let ivBlob = generateRandom(12);
64    let arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 8 bytes
65    let dataAad = new Uint8Array(arr);
66    let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
67    arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes
68    let dataTag = new Uint8Array(arr);
69    let tagBlob: cryptoFramework.DataBlob = {
70      data: dataTag
71    }; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption.
72    let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
73      iv: ivBlob,
74      aad: aadBlob,
75      authTag: tagBlob,
76      algName: "GcmParamsSpec"
77    };
78    return gcmParamsSpec;
79  }
80  let gcmParams = genGcmParamsSpec();
81  // Encrypt the message by segment.
82  async function encryptMessageUpdateBySegment(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
83    let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
84    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
85    let updateLength = 20; // Pass in 20 bytes each time. You can set this parameter as required.
86    let cipherText = new Uint8Array();
87    for (let i = 0; i < plainText.data.length; i += updateLength) {
88      let updateMessage = plainText.data.subarray(i, i + updateLength);
89      let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
90      // Call update() multiple times to pass in data by segment.
91      let updateOutput = await cipher.update(updateMessageBlob);
92      // Combine the result of each Cipher.update to obtain the ciphertext. In certain cases, the Cipher.doFinal result also needs to be combined, which depends on the cipher block mode.
93      // 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.
94      let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length);
95      mergeText.set(cipherText);
96      mergeText.set(updateOutput.data, cipherText.length);
97      cipherText = mergeText;
98    }
99    gcmParams.authTag = await cipher.doFinal(null);
100    let cipherBlob: cryptoFramework.DataBlob = { data: cipherText };
101    return cipherBlob;
102  }
103  // Decrypt the message by segment.
104  async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
105    let decoder = cryptoFramework.createCipher('AES128|GCM|PKCS7');
106    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams);
107    let updateLength = 20; // Pass in 20 bytes each time. You can set this parameter as required.
108    let decryptText = new Uint8Array();
109    for (let i = 0; i < cipherText.data.length; i += updateLength) {
110      let updateMessage = cipherText.data.subarray(i, i + updateLength);
111      let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
112      // Call update() multiple times to pass in data by segment.
113      let updateOutput = await decoder.update(updateMessageBlob);
114      // Combine the update() results to obtain the plaintext.
115      let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length);
116      mergeText.set(decryptText);
117      mergeText.set(updateOutput.data, decryptText.length);
118      decryptText = mergeText;
119    }
120    let decryptData = await decoder.doFinal(null);
121    if (decryptData === null) {
122      console.info('GCM decrypt success, decryptData is null');
123    }
124    let decryptBlob: cryptoFramework.DataBlob = { data: decryptText };
125    return decryptBlob;
126  }
127  async function genSymKeyByData(symKeyData: Uint8Array) {
128    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
129    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
130    let symKey = await aesGenerator.convertKey(symKeyBlob);
131    console.info('convertKey success');
132    return symKey;
133  }
134  async function aes() {
135    let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
136    let symKey = await genSymKeyByData(keyData);
137    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.
138    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
139    let encryptText = await encryptMessageUpdateBySegment(symKey, plainText);
140    let decryptText = await decryptMessagePromise(symKey, encryptText);
141    if (plainText.data.toString() === decryptText.data.toString()) {
142      console.info('decrypt ok');
143      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
144    } else {
145      console.error('decrypt failed');
146    }
147  }
148  ```
149
150- Example (using synchronous APIs):
151
152  ```ts
153  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
154  import { buffer } from '@kit.ArkTS';
155
156  function generateRandom(len: number) {
157    let rand = cryptoFramework.createRandom();
158    let generateRandSync = rand.generateRandomSync(len);
159    return generateRandSync;
160  }
161
162  function genGcmParamsSpec() {
163    let ivBlob = generateRandom(12);
164    let arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 8 bytes
165    let dataAad = new Uint8Array(arr);
166    let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
167    arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes
168    let dataTag = new Uint8Array(arr);
169    let tagBlob: cryptoFramework.DataBlob = {
170      data: dataTag
171    }; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption.
172    let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
173      iv: ivBlob,
174      aad: aadBlob,
175      authTag: tagBlob,
176      algName: "GcmParamsSpec"
177    };
178    return gcmParamsSpec;
179  }
180  let gcmParams = genGcmParamsSpec();
181  // Encrypt the message by segment.
182  function encryptMessageUpdateBySegment(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
183    let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
184    cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
185    let updateLength = 20; // Pass in 20 bytes each time. You can set this parameter as required.
186    let cipherText = new Uint8Array();
187    for (let i = 0; i < plainText.data.length; i += updateLength) {
188      let updateMessage = plainText.data.subarray(i, i + updateLength);
189      let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
190      // Call update() multiple times to pass in data by segment.
191      let updateOutput = cipher.updateSync(updateMessageBlob);
192      // 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
193      // 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.
194      let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length);
195      mergeText.set(cipherText);
196      mergeText.set(updateOutput.data, cipherText.length);
197      cipherText = mergeText;
198    }
199    gcmParams.authTag = cipher.doFinalSync(null);
200    let cipherBlob: cryptoFramework.DataBlob = { data: cipherText };
201    return cipherBlob;
202  }
203  // Decrypt the message by segment.
204  function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
205    let decoder = cryptoFramework.createCipher('AES128|GCM|PKCS7');
206    decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams);
207    let updateLength = 20; // Pass in 20 bytes each time. You can set this parameter as required.
208    let decryptText = new Uint8Array();
209    for (let i = 0; i < cipherText.data.length; i += updateLength) {
210      let updateMessage = cipherText.data.subarray(i, i + updateLength);
211      let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
212      // Call update() multiple times to pass in data by segment.
213      let updateOutput = decoder.updateSync(updateMessageBlob);
214      // Combine the update() results to obtain the plaintext.
215      let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length);
216      mergeText.set(decryptText);
217      mergeText.set(updateOutput.data, decryptText.length);
218      decryptText = mergeText;
219    }
220    let decryptData = decoder.doFinalSync(null);
221    if (decryptData === null) {
222      console.info('GCM decrypt success, decryptData is null');
223    }
224    let decryptBlob: cryptoFramework.DataBlob = { data: decryptText };
225    return decryptBlob;
226  }
227  function genSymKeyByData(symKeyData: Uint8Array) {
228    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
229    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
230    let symKey = aesGenerator.convertKeySync(symKeyBlob);
231    console.info('convertKeySync success');
232    return symKey;
233  }
234  function main() {
235    let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
236    let symKey = genSymKeyByData(keyData);
237    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.
238    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
239    let encryptText = encryptMessageUpdateBySegment(symKey, plainText);
240    let decryptText = decryptMessage(symKey, encryptText);
241    if (plainText.data.toString() === decryptText.data.toString()) {
242      console.info('decrypt ok');
243      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
244    } else {
245      console.error('decrypt failed');
246    }
247  }
248
249  ```
250