1e41f4b71Sopenharmony_ci# Encryption and Decryption by Segment with an SM4 Symmetric Key (GCM Mode) (C/C++)
2e41f4b71Sopenharmony_ci
3e41f4b71Sopenharmony_ci
4e41f4b71Sopenharmony_ciFor details about the algorithm specifications, see [SM4](crypto-sym-encrypt-decrypt-spec.md#sm4).
5e41f4b71Sopenharmony_ci
6e41f4b71Sopenharmony_ci
7e41f4b71Sopenharmony_ci## Adding the Dynamic Library in the CMake Script
8e41f4b71Sopenharmony_ci```txt
9e41f4b71Sopenharmony_ci   target_link_libraries(entry PUBLIC libohcrypto.so)
10e41f4b71Sopenharmony_ci```
11e41f4b71Sopenharmony_ci
12e41f4b71Sopenharmony_ci**Encryption**
13e41f4b71Sopenharmony_ci
14e41f4b71Sopenharmony_ci
15e41f4b71Sopenharmony_ci1. 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**).
16e41f4b71Sopenharmony_ci   
17e41f4b71Sopenharmony_ci   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.
18e41f4b71Sopenharmony_ci
19e41f4b71Sopenharmony_ci2. 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**.
20e41f4b71Sopenharmony_ci
21e41f4b71Sopenharmony_ci3. 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_SetParams](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipherparams_setparam) to set cipher parameters.
22e41f4b71Sopenharmony_ci
23e41f4b71Sopenharmony_ci4. 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.
24e41f4b71Sopenharmony_ci
25e41f4b71Sopenharmony_ci5. 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.
26e41f4b71Sopenharmony_ci
27e41f4b71Sopenharmony_ci   - 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.
28e41f4b71Sopenharmony_ci   - 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.
29e41f4b71Sopenharmony_ci
30e41f4b71Sopenharmony_ci      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.
31e41f4b71Sopenharmony_ci
32e41f4b71Sopenharmony_ci      If a stream cipher mode (CTR or OFB) is used, the ciphertext length is usually the same as the plaintext length.
33e41f4b71Sopenharmony_ci
34e41f4b71Sopenharmony_ci6. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the ciphertext.
35e41f4b71Sopenharmony_ci   
36e41f4b71Sopenharmony_ci   - If data has been passed in by **OH_CryptoSymCipher_Update()**, pass in **null** in the **data** parameter of **OH_CryptoSymCipher_Final**.
37e41f4b71Sopenharmony_ci   - The output of **OH_CryptoSymCipher_Final** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
38e41f4b71Sopenharmony_ci
39e41f4b71Sopenharmony_ci7. 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.
40e41f4b71Sopenharmony_ci   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.
41e41f4b71Sopenharmony_ci
42e41f4b71Sopenharmony_ci8. 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.
43e41f4b71Sopenharmony_ci
44e41f4b71Sopenharmony_ci
45e41f4b71Sopenharmony_ci**Decryption**
46e41f4b71Sopenharmony_ci
47e41f4b71Sopenharmony_ci
48e41f4b71Sopenharmony_ci1. 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.
49e41f4b71Sopenharmony_ci
50e41f4b71Sopenharmony_ci2. 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.
51e41f4b71Sopenharmony_ci
52e41f4b71Sopenharmony_ci3. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the plaintext.
53e41f4b71Sopenharmony_ci
54e41f4b71Sopenharmony_ci**Example**
55e41f4b71Sopenharmony_ci
56e41f4b71Sopenharmony_ci```c++
57e41f4b71Sopenharmony_ci#include <string.h>
58e41f4b71Sopenharmony_ci#include "CryptoArchitectureKit/crypto_common.h"
59e41f4b71Sopenharmony_ci#include "CryptoArchitectureKit/crypto_sym_cipher.h"
60e41f4b71Sopenharmony_ci
61e41f4b71Sopenharmony_ci#define OH_CRYPTO_GCM_TAG_LEN 16
62e41f4b71Sopenharmony_cistatic OH_Crypto_ErrCode doTestSm4GcmSeg()
63e41f4b71Sopenharmony_ci{
64e41f4b71Sopenharmony_ci    OH_CryptoSymKeyGenerator *genCtx = nullptr;
65e41f4b71Sopenharmony_ci    OH_CryptoSymCipher *encCtx = nullptr;
66e41f4b71Sopenharmony_ci    OH_CryptoSymCipher *decCtx = nullptr;
67e41f4b71Sopenharmony_ci    OH_CryptoSymKey *keyCtx = nullptr;
68e41f4b71Sopenharmony_ci    OH_CryptoSymCipherParams *params = nullptr;
69e41f4b71Sopenharmony_ci
70e41f4b71Sopenharmony_ci    uint8_t plainText[] = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee";
71e41f4b71Sopenharmony_ci    Crypto_DataBlob msgBlob = {.data = reinterpret_cast<uint8_t *>(plainText), .len = sizeof(plainText)};
72e41f4b71Sopenharmony_ci
73e41f4b71Sopenharmony_ci    uint8_t aad[8] = {0};
74e41f4b71Sopenharmony_ci    uint8_t tagArr[16] = {0};
75e41f4b71Sopenharmony_ci    uint8_t iv[12] = {0};
76e41f4b71Sopenharmony_ci    Crypto_DataBlob tag = {.data = nullptr, .len = 0};
77e41f4b71Sopenharmony_ci    Crypto_DataBlob ivBlob = {.data = iv, .len = sizeof(iv)};
78e41f4b71Sopenharmony_ci    Crypto_DataBlob aadBlob = {.data = aad, .len = sizeof(aad)};
79e41f4b71Sopenharmony_ci    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
80e41f4b71Sopenharmony_ci    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
81e41f4b71Sopenharmony_ci    Crypto_DataBlob tagInit = {.data = tagArr, .len = sizeof(tagArr)};
82e41f4b71Sopenharmony_ci    int32_t cipherLen = 0;
83e41f4b71Sopenharmony_ci    int blockSize = 20;
84e41f4b71Sopenharmony_ci    int32_t randomLen = sizeof(plainText);
85e41f4b71Sopenharmony_ci    int cnt = randomLen / blockSize;
86e41f4b71Sopenharmony_ci    int rem = randomLen % blockSize;
87e41f4b71Sopenharmony_ci    uint8_t cipherText[sizeof(plainText) + 16] = {0};
88e41f4b71Sopenharmony_ci    Crypto_DataBlob cipherBlob = {.data = reinterpret_cast<uint8_t *>(cipherText), .len = (size_t)cipherLen};
89e41f4b71Sopenharmony_ci
90e41f4b71Sopenharmony_ci    // Generate a key.
91e41f4b71Sopenharmony_ci    OH_Crypto_ErrCode ret;
92e41f4b71Sopenharmony_ci    ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx);
93e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
94e41f4b71Sopenharmony_ci        goto end;
95e41f4b71Sopenharmony_ci    }
96e41f4b71Sopenharmony_ci    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
97e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
98e41f4b71Sopenharmony_ci        goto end;
99e41f4b71Sopenharmony_ci    }
100e41f4b71Sopenharmony_ci
101e41f4b71Sopenharmony_ci    // Set parameters.
102e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipherParams_Create(&params);
103e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
104e41f4b71Sopenharmony_ci        goto end;
105e41f4b71Sopenharmony_ci    }
106e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivBlob);
107e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
108e41f4b71Sopenharmony_ci        goto end;
109e41f4b71Sopenharmony_ci    }
110e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadBlob);
111e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
112e41f4b71Sopenharmony_ci        goto end;
113e41f4b71Sopenharmony_ci    }
114e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagInit);
115e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
116e41f4b71Sopenharmony_ci        goto end;
117e41f4b71Sopenharmony_ci    }
118e41f4b71Sopenharmony_ci
119e41f4b71Sopenharmony_ci    // Encrypt data.
120e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &encCtx);
121e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
122e41f4b71Sopenharmony_ci        goto end;
123e41f4b71Sopenharmony_ci    }
124e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
125e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
126e41f4b71Sopenharmony_ci        goto end;
127e41f4b71Sopenharmony_ci    }
128e41f4b71Sopenharmony_ci
129e41f4b71Sopenharmony_ci    for (int i = 0; i < cnt; i++) {
130e41f4b71Sopenharmony_ci        msgBlob.len = blockSize;
131e41f4b71Sopenharmony_ci        ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate);
132e41f4b71Sopenharmony_ci        if (ret != CRYPTO_SUCCESS) {
133e41f4b71Sopenharmony_ci            goto end;
134e41f4b71Sopenharmony_ci        }
135e41f4b71Sopenharmony_ci        msgBlob.data += blockSize;
136e41f4b71Sopenharmony_ci        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
137e41f4b71Sopenharmony_ci        cipherLen += outUpdate.len;
138e41f4b71Sopenharmony_ci    }
139e41f4b71Sopenharmony_ci    if (rem > 0) {
140e41f4b71Sopenharmony_ci        msgBlob.len = rem;
141e41f4b71Sopenharmony_ci        ret = OH_CryptoSymCipher_Update(encCtx, (Crypto_DataBlob *)&msgBlob, &outUpdate);
142e41f4b71Sopenharmony_ci        if (ret != CRYPTO_SUCCESS) {
143e41f4b71Sopenharmony_ci            goto end;
144e41f4b71Sopenharmony_ci        }
145e41f4b71Sopenharmony_ci        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
146e41f4b71Sopenharmony_ci        cipherLen += outUpdate.len;
147e41f4b71Sopenharmony_ci    }
148e41f4b71Sopenharmony_ci    cipherBlob.len = cipherLen;
149e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tag);
150e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
151e41f4b71Sopenharmony_ci        goto end;
152e41f4b71Sopenharmony_ci    }
153e41f4b71Sopenharmony_ci    
154e41f4b71Sopenharmony_ci    // Decrypt data.
155e41f4b71Sopenharmony_ci    msgBlob.data -= sizeof(plainText) - rem;
156e41f4b71Sopenharmony_ci    msgBlob.len = sizeof(plainText);
157e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &decCtx);
158e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
159e41f4b71Sopenharmony_ci        goto end;
160e41f4b71Sopenharmony_ci    }
161e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tag);
162e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
163e41f4b71Sopenharmony_ci        goto end;
164e41f4b71Sopenharmony_ci    }
165e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
166e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
167e41f4b71Sopenharmony_ci        goto end;
168e41f4b71Sopenharmony_ci    }
169e41f4b71Sopenharmony_ci    ret = OH_CryptoSymCipher_Final(decCtx, &cipherBlob, &decUpdate);
170e41f4b71Sopenharmony_ci    if (ret != CRYPTO_SUCCESS) {
171e41f4b71Sopenharmony_ci        goto end;
172e41f4b71Sopenharmony_ci    }
173e41f4b71Sopenharmony_ci    if (memcmp(msgBlob.data, decUpdate.data, msgBlob.len) == 0) {
174e41f4b71Sopenharmony_ci        ret = (OH_Crypto_ErrCode)1234567;
175e41f4b71Sopenharmony_ci    } else {
176e41f4b71Sopenharmony_ci        ret = (OH_Crypto_ErrCode)456;
177e41f4b71Sopenharmony_ci    }
178e41f4b71Sopenharmony_ciend:
179e41f4b71Sopenharmony_ci    OH_CryptoSymCipherParams_Destroy(params);
180e41f4b71Sopenharmony_ci    OH_CryptoSymCipher_Destroy(encCtx);
181e41f4b71Sopenharmony_ci    OH_CryptoSymCipher_Destroy(decCtx);
182e41f4b71Sopenharmony_ci    OH_CryptoSymKeyGenerator_Destroy(genCtx);
183e41f4b71Sopenharmony_ci    OH_CryptoSymKey_Destroy(keyCtx);
184e41f4b71Sopenharmony_ci    OH_Crypto_FreeDataBlob(&outUpdate);
185e41f4b71Sopenharmony_ci    OH_Crypto_FreeDataBlob(&tag);
186e41f4b71Sopenharmony_ci    OH_Crypto_FreeDataBlob(&decUpdate);
187e41f4b71Sopenharmony_ci    return ret;
188e41f4b71Sopenharmony_ci}
189e41f4b71Sopenharmony_ci```
190