1# Encryption and Decryption by Segment 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-ndk.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. Set the size of the data to be passed in each time to 20 bytes, and call [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_update) multiple times to pass in 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   - You are advised to check the result of each **OH_CryptoSymCipher_Update()**. If the result is not **null**, obtain the data and combine the data segments into complete ciphertext. The **OH_CryptoSymCipher_Update()** result may vary with the key specifications.
29
30      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 **OH_CryptoSymCipher_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 **OH_CryptoSymCipher_Update()** to form a block. When **OH_CryptoSymCipher_Final()** is called, the unencrypted data is padded to the block size based on the specified padding mode, and then encrypted. The **OH_CryptoSymCipher_Update()** API works in the same way in decryption.
31
32      If a stream cipher mode (CTR or OFB) is used, the ciphertext length is usually the same as the plaintext length.
33
346. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the ciphertext.
35
36   - If data has been passed in by **OH_CryptoSymCipher_Update()**, pass in **null** in the **data** parameter of **OH_CryptoSymCipher_Final**.
37   - The output of **OH_CryptoSymCipher_Final** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
38
397. 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.
40   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.
41
428. 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.
43
44
45**Decryption**
46
47
481. 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_DECRYPT_MODE**, and specify the key for decryption (**OH_CryptoSymKey**) and the decryption parameter instance (**OH_CryptoSymCipherParams**) corresponding to the GCM mode.
49
502. Set the size of the data to be passed in each time to 20 bytes, and call [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_update) multiple times to pass in the data (ciphertext) to be decrypted.
51
523. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the plaintext.
53
54
55**Example**
56
57```c++
58#include <string.h>
59#include "CryptoArchitectureKit/crypto_common.h"
60#include "CryptoArchitectureKit/crypto_sym_cipher.h"
61#include <string.h>
62
63#define OH_CRYPTO_GCM_TAG_LEN 16
64#define OH_CRYPTO_MAX_TEST_DATA_LEN 128
65static OH_Crypto_ErrCode doTestSm4GcmSeg()
66{
67    OH_CryptoSymKeyGenerator *genCtx = nullptr;
68    OH_CryptoSymCipher *encCtx = nullptr;
69    OH_CryptoSymCipher *decCtx = nullptr;
70    OH_CryptoSymKey *keyCtx = nullptr;
71    OH_CryptoSymCipherParams *params = nullptr;
72
73    char *plainText = const_cast<char *>("aaaaa.....bbbbb.....ccccc.....ddddd.....eee");
74    Crypto_DataBlob msgBlob = {.data = (uint8_t *)(plainText), .len = strlen(plainText)};
75    uint8_t aad[8] = {1, 2, 3, 4, 5, 6, 7, 8};
76    uint8_t tagArr[16] = {0};
77    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.
78    Crypto_DataBlob tag = {.data = nullptr, .len = 0};
79    Crypto_DataBlob ivBlob = {.data = iv, .len = sizeof(iv)};
80    Crypto_DataBlob aadBlob = {.data = aad, .len = sizeof(aad)};
81    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
82    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
83    Crypto_DataBlob tagInit = {.data = tagArr, .len = sizeof(tagArr)};
84    int32_t cipherLen = 0;
85    int blockSize = 20;
86    int32_t randomLen = strlen(plainText);
87    int cnt = randomLen / blockSize;
88    int rem = randomLen % blockSize;
89    uint8_t cipherText[OH_CRYPTO_MAX_TEST_DATA_LEN] = {0};
90    Crypto_DataBlob cipherBlob;
91
92    // Generate a key.
93    OH_Crypto_ErrCode ret;
94    ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx);
95    if (ret != CRYPTO_SUCCESS) {
96        goto end;
97    }
98    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
99    if (ret != CRYPTO_SUCCESS) {
100        goto end;
101    }
102
103    // Set parameters.
104    ret = OH_CryptoSymCipherParams_Create(&params);
105    if (ret != CRYPTO_SUCCESS) {
106        goto end;
107    }
108    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivBlob);
109    if (ret != CRYPTO_SUCCESS) {
110        goto end;
111    }
112    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadBlob);
113    if (ret != CRYPTO_SUCCESS) {
114        goto end;
115    }
116    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagInit);
117    if (ret != CRYPTO_SUCCESS) {
118        goto end;
119    }
120
121    // Encrypt data.
122    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &encCtx);
123    if (ret != CRYPTO_SUCCESS) {
124        goto end;
125    }
126    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
127    if (ret != CRYPTO_SUCCESS) {
128        goto end;
129    }
130
131    for (int i = 0; i < cnt; i++) {
132        msgBlob.len = blockSize;
133        ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate);
134        if (ret != CRYPTO_SUCCESS) {
135            goto end;
136        }
137        msgBlob.data += blockSize;
138        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
139        cipherLen += outUpdate.len;
140    }
141    if (rem > 0) {
142        msgBlob.len = rem;
143        ret = OH_CryptoSymCipher_Update(encCtx, (Crypto_DataBlob *)&msgBlob, &outUpdate);
144        if (ret != CRYPTO_SUCCESS) {
145            goto end;
146        }
147        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
148        cipherLen += outUpdate.len;
149    }
150    ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tag);
151    if (ret != CRYPTO_SUCCESS) {
152        goto end;
153    }
154
155    // Decrypt data.
156    cipherBlob = {.data = reinterpret_cast<uint8_t *>(cipherText), .len = (size_t)cipherLen};
157    msgBlob.data -= strlen(plainText) - rem;
158    msgBlob.len = strlen(plainText);
159    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &decCtx);
160    if (ret != CRYPTO_SUCCESS) {
161        goto end;
162    }
163    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tag);
164    if (ret != CRYPTO_SUCCESS) {
165        goto end;
166    }
167    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
168    if (ret != CRYPTO_SUCCESS) {
169        goto end;
170    }
171    ret = OH_CryptoSymCipher_Final(decCtx, &cipherBlob, &decUpdate);
172    if (ret != CRYPTO_SUCCESS) {
173        goto end;
174    }
175end:
176    OH_CryptoSymCipherParams_Destroy(params);
177    OH_CryptoSymCipher_Destroy(encCtx);
178    OH_CryptoSymCipher_Destroy(decCtx);
179    OH_CryptoSymKeyGenerator_Destroy(genCtx);
180    OH_CryptoSymKey_Destroy(keyCtx);
181    OH_Crypto_FreeDataBlob(&outUpdate);
182    OH_Crypto_FreeDataBlob(&tag);
183    OH_Crypto_FreeDataBlob(&decUpdate);
184    return ret;
185}
186```
187