1# Encryption and Decryption with an SM4 Symmetric Key (CBC Mode) (ArkTS)
2
3
4For details about the algorithm specifications, see [SM4](crypto-sym-encrypt-decrypt-spec.md#sm4).
5
6**Encryption**
7
8
91. 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**).
10
11   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.
12
132. Use [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'SM4_128|CBC|PKCS7'** to create a **Cipher** instance. The key type is **SM4_128**, block cipher mode is **CBC**, and the padding mode is **PKCS7**.
14
153. 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 **IvParamsSpec** corresponding to the CBC mode.
16
174. Use [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be encrypted (plaintext).
18
19   - If a small amount of data is to be encrypted, you can use **Cipher.doFinal** immediately after **Cipher.init**.
20   - If a large amount of data is to be encrypted, you can call **Cipher.update** multiple times to pass in the data by segment.
21
225. Use [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the encrypted data.
23
24   - If data has been passed in by **Cipher.update**, pass in **null** in the **data** parameter of **Cipher.doFinal**.
25   - The output of **Cipher.doFinal** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
26
27
28**Decryption**
29
30
311. 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 **IvParamsSpec** corresponding to the CBC mode.
32
332. Use [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be decrypted (ciphertext).
34
353. Use [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data.
36
37
38- Example (using asynchronous APIs):
39
40  ```ts
41  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
42  import { buffer } from '@kit.ArkTS';
43
44  function generateRandom(len: number) {
45    let rand = cryptoFramework.createRandom();
46    let generateRandSync = rand.generateRandomSync(len);
47    return generateRandSync;
48  }
49
50  function genIvParamsSpec() {
51    let ivBlob = generateRandom(16); // 16 bytes
52    let ivParamsSpec: cryptoFramework.IvParamsSpec = {
53      algName: "IvParamsSpec",
54      iv: ivBlob
55    };
56    return ivParamsSpec;
57  }
58  let iv = genIvParamsSpec();
59  // Encrypt the message.
60  async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
61    let cipher = cryptoFramework.createCipher('SM4_128|CBC|PKCS7');
62    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
63    let encryptData = await cipher.doFinal(plainText);
64    return encryptData;
65  }
66  // Decrypt the message.
67  async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
68    let decoder = cryptoFramework.createCipher('SM4_128|CBC|PKCS7');
69    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
70    let decryptData = await decoder.doFinal(cipherText);
71    return decryptData;
72  }
73  async function genSymKeyByData(symKeyData: Uint8Array) {
74    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
75    let symGenerator = cryptoFramework.createSymKeyGenerator('SM4_128');
76    let symKey = await symGenerator.convertKey(symKeyBlob);
77    console.info('convertKey success');
78    return symKey;
79  }
80  async function main() {
81    try {
82      let keyData = new Uint8Array([7, 154, 52, 176, 4, 236, 150, 43, 237, 9, 145, 166, 141, 174, 224, 131]);
83      let symKey = await genSymKeyByData(keyData);
84      let message = "This is a test";
85      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
86      let encryptText = await encryptMessagePromise(symKey, plainText);
87      let decryptText = await decryptMessagePromise(symKey, encryptText);
88      if (plainText.data.toString() === decryptText.data.toString()) {
89        console.info('decrypt ok');
90        console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
91      } else {
92        console.error('decrypt failed');
93      }
94    } catch (error) {
95      console.error(`SM4 "${error}", error code: ${error.code}`);
96    }
97  }
98  ```
99
100- Example (using synchronous APIs):
101
102  ```ts
103  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
104  import { buffer } from '@kit.ArkTS';
105
106  function generateRandom(len: number) {
107    let rand = cryptoFramework.createRandom();
108    let generateRandSync = rand.generateRandomSync(len);
109    return generateRandSync;
110  }
111
112  function genIvParamsSpec() {
113    let ivBlob = generateRandom(16); // 16 bytes
114    let ivParamsSpec: cryptoFramework.IvParamsSpec = {
115      algName: "IvParamsSpec",
116      iv: ivBlob
117    };
118    return ivParamsSpec;
119  }
120  let iv = genIvParamsSpec();
121  // Encrypt the message.
122  function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
123    let cipher = cryptoFramework.createCipher('SM4_128|CBC|PKCS7');
124    cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
125    let encryptData = cipher.doFinalSync(plainText);
126    return encryptData;
127  }
128  // Decrypt the message.
129  function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
130    let decoder = cryptoFramework.createCipher('SM4_128|CBC|PKCS7');
131    decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
132    let decryptData = decoder.doFinalSync(cipherText);
133    return decryptData;
134  }
135  function genSymKeyByData(symKeyData: Uint8Array) {
136    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
137    let symGenerator = cryptoFramework.createSymKeyGenerator('SM4_128');
138    let symKey = symGenerator.convertKeySync(symKeyBlob);
139    console.info('convertKeySync success');
140    return symKey;
141  }
142  function main() {
143    try {
144      let keyData = new Uint8Array([7, 154, 52, 176, 4, 236, 150, 43, 237, 9, 145, 166, 141, 174, 224, 131]);
145      let symKey = genSymKeyByData(keyData);
146      let message = "This is a test";
147      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
148      let encryptText = encryptMessage(symKey, plainText);
149      let decryptText = decryptMessage(symKey, encryptText);
150      if (plainText.data.toString() === decryptText.data.toString()) {
151        console.info('decrypt ok');
152        console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
153      } else {
154        console.error('decrypt failed');
155      }
156    } catch (error) {
157      console.error(`SM4 "${error}", error code: ${error.code}`);
158    }
159  }
160  ```
161