1# Encryption and Decryption with an SM4 Symmetric Key (GCM Mode) (C/C++)
2
3
4For details about the algorithm specifications, see [SM4](crypto-sym-encrypt-decrypt-spec.md#sm4).
5
6
7## Adding the Dynamic Library in the CMake Script
8```txt
9   target_link_libraries(entry PUBLIC libohcrypto.so)
10```
11
12**Encryption**
13
14
151. Use [OH_CryptoSymKeyGenerator_Create](../../reference/apis-crypto-architecture-kit/_crypto_sym_key_api.md#oh_cryptosymkeygenerator_create) and [OH_CryptoSymKeyGenerator_Generate](../../reference/apis-crypto-architecture-kit/_crypto_sym_key_api.md#oh_cryptosymkeygenerator_generate) to generate a 128-bit SM4 symmetric key (**OH_CryptoSymKey**).
16
17   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.
18
192. Use [OH_CryptoSymCipher_Create](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_create) 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**.
20
213. Use [OH_CryptoSymCipherParams_Create](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_create) to create a symmetric cipher parameter instance, and use [OH_CryptoSymCipherParams_SetParam](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_setparam) to set cipher parameters.
22
234. Use [OH_CryptoSymCipher_Init](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_init) to initialize the **Cipher** instance. Specifically, set **mode** to **CRYPTO_ENCRYPT_MODE**, and specify the key for encryption (**OH_CryptoSymKey**) and the encryption parameter instance (**OH_CryptoSymCipherParams**) corresponding to the GCM mode.
24
255. Use [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_update) to update the data (plaintext) to be encrypted.
26
27   Currently, the amount of data to be passed in by a single **OH_CryptoSymCipher_Update()** is not limited. You can determine how to pass in data based on the data volume.
28
29   - If a small amount of data is to be encrypted, you can use **OH_CryptoSymCipher_Final()** immediately after **OH_CryptoSymCipher_Init()**.
30   - If a large amount of data is to be encrypted, you can call **OH_CryptoSymCipher_Update()** multiple times to pass in the data by segment.
31
326. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the ciphertext.
33   - If data has been passed in by **OH_CryptoSymCipher_Update()**, pass in **null** in the **data** parameter of **OH_CryptoSymCipher_Final**.
34   - The output of **OH_CryptoSymCipher_Final** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
35
367. Use [OH_CryptoSymCipherParams_Create](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_create) to create a **Params** instance, and use [OH_CryptoSymCipherParams_SetParam](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_setparam) to set **authTag** as the authentication information for decryption. 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.
37
388. Use [OH_CryptoSymKeyGenerator_Destroy](../../reference/apis-crypto-architecture-kit/_crypto_sym_key_api.md#oh_cryptosymkeygenerator_destroy), [OH_CryptoSymCipher_Destroy](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_destroy), and [OH_CryptoSymCipherParams_Destroy](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_destroy) to destroy the instances created.
39
40
41**Decryption**
42
43
441. Use [OH_CryptoSymCipher_Init](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_init) initializes the **Cipher** instance. Specifically, set **mode** to **CRYPTO_DECRYPT_MODE**, and specify the key for decryption (**OH_CryptoSymKey**) and the decryption parameter instance (**OH_CryptoSymCipherParams**) corresponding to the GCM mode.
45
462. Use [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_update) to update the data (ciphertext) to be decrypted.
47
483. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the plaintext.
49
50
51**Example**
52
53```c++
54#include "CryptoArchitectureKit/crypto_common.h"
55#include "CryptoArchitectureKit/crypto_sym_cipher.h"
56#include <string.h>
57
58static OH_Crypto_ErrCode doTestSm4Gcm()
59{
60    OH_CryptoSymKeyGenerator *genCtx = nullptr;
61    OH_CryptoSymCipher *encCtx = nullptr;
62    OH_CryptoSymCipher *decCtx = nullptr;
63    OH_CryptoSymKey *keyCtx = nullptr;
64    OH_CryptoSymCipherParams *params = nullptr;
65
66    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
67    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
68
69    uint8_t aad[8] = {1, 2, 3, 4, 5, 6, 7, 8};
70    uint8_t tag[16] = {0};
71    uint8_t iv[12] = {1, 2, 4, 12, 3, 4, 2, 3, 3, 2, 0, 4}; // iv is generated from an array of secure random numbers.
72    Crypto_DataBlob ivData = {.data = iv, .len = sizeof(iv)};
73    Crypto_DataBlob aadData = {.data = aad, .len = sizeof(aad)};
74    Crypto_DataBlob tagData = {.data = tag, .len = sizeof(tag)};
75    Crypto_DataBlob tagOutPut = {.data = nullptr, .len = 0};
76    char *plainText = const_cast<char *>("this is test!");
77    Crypto_DataBlob msgBlob = {.data = (uint8_t *)(plainText), .len = strlen(plainText)};
78    // Generate a symmetric key.
79    OH_Crypto_ErrCode ret;
80    ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx);
81    if (ret != CRYPTO_SUCCESS) {
82        goto end;
83    }
84    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
85    if (ret != CRYPTO_SUCCESS) {
86        goto end;
87    }
88
89    // Set parameters.
90    ret = OH_CryptoSymCipherParams_Create(&params);
91    if (ret != CRYPTO_SUCCESS) {
92        goto end;
93    }
94    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivData);
95    if (ret != CRYPTO_SUCCESS) {
96        goto end;
97    }
98    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadData);
99    if (ret != CRYPTO_SUCCESS) {
100        goto end;
101    }
102    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagData);
103    if (ret != CRYPTO_SUCCESS) {
104        goto end;
105    }
106
107    // Encrypt data.
108    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &encCtx);
109    if (ret != CRYPTO_SUCCESS) {
110        goto end;
111    }
112    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
113    if (ret != CRYPTO_SUCCESS) {
114        goto end;
115    }
116    ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate);
117    if (ret != CRYPTO_SUCCESS) {
118        goto end;
119    }
120    ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tagOutPut);
121    if (ret != CRYPTO_SUCCESS) {
122        goto end;
123    }
124
125    // Decrypt data.
126    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &decCtx);
127    if (ret != CRYPTO_SUCCESS) {
128        goto end;
129    }
130    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagOutPut);
131    if (ret != CRYPTO_SUCCESS) {
132        goto end;
133    }
134    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
135    if (ret != CRYPTO_SUCCESS) {
136        goto end;
137    }
138    ret = OH_CryptoSymCipher_Final(decCtx, &outUpdate, &decUpdate);
139    if (ret != CRYPTO_SUCCESS) {
140        goto end;
141    }
142
143    // Release resources.
144end:
145    OH_CryptoSymCipherParams_Destroy(params);
146    OH_CryptoSymCipher_Destroy(encCtx);
147    OH_CryptoSymCipher_Destroy(decCtx);
148    OH_CryptoSymKeyGenerator_Destroy(genCtx);
149    OH_CryptoSymKey_Destroy(keyCtx);
150    OH_Crypto_FreeDataBlob(&outUpdate);
151    OH_Crypto_FreeDataBlob(&decUpdate);
152    OH_Crypto_FreeDataBlob(&tagOutPut);
153    return ret;
154}
155```
156