• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Encryption and Decryption with an SM4 Symmetric Key (ECB 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. 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 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. Call [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'SM4_128|ECB|PKCS7'** to create a **Cipher** instance for encryption. The key type is **SM4_128**, block cipher mode is **ECB**, and the padding mode is **PKCS7**.
14
153. Call [Cipher.init](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#init-1) to initialize the **Cipher** instance. In **Cipher.init**, set **opMode** to **CryptoMode.ENCRYPT_MODE** (encryption) and **key** to **SymKey** (the key used for encryption).
16
17   When ECB mode is used, pass in **null** in **params**.
18
194. Call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be encrypted (plaintext).
20
21   - If a small amount of data is to be encrypted, you can use **Cipher.doFinal** immediately after **Cipher.init**.
22   - If a large amount of data is to be encrypted, you can call **Cipher.update** multiple times to pass in the data by segment.
23
245. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the encrypted data.
25
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
29
30**Decryption**
31
321. Call [cryptoFramework.createCipher](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatecipher) with the string parameter **'SM4_128|ECB|PKCS7'** to create a **Cipher** instance for decryption. The key type is **SM4_128**, block cipher mode is **ECB**, and the padding mode is **PKCS7**.
33
342. Call [Cipher.init](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#init-1) to initialize the **Cipher** instance. In **Cipher.init**, set **opMode** to **CryptoMode.DECRYPT_MODE** (decryption) and **key** to **SymKey** (the key used for decryption). When ECB mode is used, pass in **null** in **params**.
35
363. Call [Cipher.update](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#update-1) to pass in the data to be decrypted (ciphertext).
37
384. Call [Cipher.doFinal](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#dofinal-1) to obtain the decrypted data.
39
40
41- Example (using asynchronous APIs):
42
43  ```ts
44  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
45  import { buffer } from '@kit.ArkTS';
46
47  // Encrypt the message.
48  async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
49    let cipher = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
50    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null);
51    let encryptData = await cipher.doFinal(plainText);
52    return encryptData;
53  }
54  // Decrypt the message.
55  async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
56    let decoder = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
57    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
58    let decryptData = await decoder.doFinal(cipherText);
59    return decryptData;
60  }
61  async function genSymKeyByData(symKeyData: Uint8Array) {
62    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
63    let symGenerator = cryptoFramework.createSymKeyGenerator('SM4_128');
64    let symKey = await symGenerator.convertKey(symKeyBlob);
65    console.info('convertKey success');
66    return symKey;
67  }
68  async function main() {
69    let keyData = new Uint8Array([7, 154, 52, 176, 4, 236, 150, 43, 237, 9, 145, 166, 141, 174, 224, 131]);
70    let symKey = await genSymKeyByData(keyData);
71    let message = "This is a test";
72    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
73    let encryptText = await encryptMessagePromise(symKey, plainText);
74    let decryptText = await decryptMessagePromise(symKey, encryptText);
75    if (plainText.data.toString() === decryptText.data.toString()) {
76      console.info('decrypt ok');
77      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
78    } else {
79      console.error('decrypt failed');
80    }
81  }
82  ```
83
84- Example (using synchronous APIs):
85
86  ```ts
87  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
88  import { buffer } from '@kit.ArkTS';
89
90  // Encrypt the message.
91  function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
92    let cipher = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
93    cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null);
94    let encryptData = cipher.doFinalSync(plainText);
95    return encryptData;
96  }
97  // Decrypt the message.
98  function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
99    let decoder = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
100    decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
101    let decryptData = decoder.doFinalSync(cipherText);
102    return decryptData;
103  }
104  function genSymKeyByData(symKeyData: Uint8Array) {
105    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
106    let symGenerator = cryptoFramework.createSymKeyGenerator('SM4_128');
107    let symKey = symGenerator.convertKeySync(symKeyBlob);
108    console.info('convertKeySync success');
109    return symKey;
110  }
111  function main() {
112    let keyData = new Uint8Array([7, 154, 52, 176, 4, 236, 150, 43, 237, 9, 145, 166, 141, 174, 224, 131]);
113    let symKey = genSymKeyByData(keyData);
114    let message = "This is a test";
115    let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
116    let encryptText = encryptMessage(symKey, plainText);
117    let decryptText = decryptMessage(symKey, encryptText);
118    if (plainText.data.toString() === decryptText.data.toString()) {
119      console.info('decrypt ok');
120      console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
121    } else {
122      console.error('decrypt failed');
123    }
124  }
125  ```
126