1# Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode) (C/C++)
2
3
4For details about the algorithm specifications, see [AES](crypto-sym-encrypt-decrypt-spec.md#aes).
5
6
7## Adding the Dynamic Library in the CMake Script
8```txt
9   target_link_libraries(entry PUBLIC libohcrypto.so)
10```
11
12## How to Develop
13
14**Encryption**
15
16
171. 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 AES symmetric key (**OH_CryptoSymKey**).
18
19   In addition to the example in this topic, [AES](crypto-sym-key-generation-conversion-spec.md#aes) and [Randomly Generating a Symmetric Key](crypto-generate-sym-key-randomly-ndk.md) may help you better understand how to generate an AES symmetric key. Note that the input parameters in the reference documents may be different from those in the example below.
20
212. Use [OH_CryptoSymCipher_Create](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_create) with the string parameter **'AES128|GCM|PKCS7'** to create a **Cipher** instance. The key type is **AES128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**.
22
233. 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.
24
254. 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.
26
275. 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.
28
29   - 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.
30   - 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.
31
32      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_Update()** 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.
33
34      If a stream cipher mode (CTR or OFB) is used, the ciphertext length is usually the same as the plaintext length.
35
366. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the ciphertext.
37
38   - If data has been passed in by **OH_CryptoSymCipher_Update()**, pass in **null** in the **data** parameter of **OH_CryptoSymCipher_Final**.
39   - The output of **OH_CryptoSymCipher_Final** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
40
417. 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.
42
43   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.
44
458. 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.
46
47**Decryption**
48
49
501. 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.
51
522. 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.
53
543. Use [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/_crypto_sym_cipher_api.md#oh_cryptosymcipher_final) to generate the plaintext.
55
56**Example**
57
58```c++
59#include <string.h>
60#include "CryptoArchitectureKit/crypto_common.h"
61#include "CryptoArchitectureKit/crypto_sym_cipher.h"
62
63#define OH_CRYPTO_GCM_TAG_LEN 16
64#define OH_CRYPTO_MAX_TEST_DATA_LEN 128
65static OH_Crypto_ErrCode doTestAesGcmSeg()
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
76    uint8_t aad[8] = {1, 2, 3, 4, 5, 6, 7, 8};
77    uint8_t tagArr[16] = {0};
78    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.
79    Crypto_DataBlob tag = {.data = nullptr, .len = 0};
80    Crypto_DataBlob ivBlob = {.data = iv, .len = sizeof(iv)};
81    Crypto_DataBlob aadBlob = {.data = aad, .len = sizeof(aad)};
82    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
83    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
84    Crypto_DataBlob tagInit = {.data = tagArr, .len = sizeof(tagArr)};
85    int32_t cipherLen = 0;
86    int blockSize = 20;
87    int32_t randomLen = strlen(plainText);
88    int cnt = randomLen / blockSize;
89    int rem = randomLen % blockSize;
90    uint8_t cipherText[OH_CRYPTO_MAX_TEST_DATA_LEN] = {0};
91    Crypto_DataBlob cipherBlob;
92
93    // Generate a key.
94    OH_Crypto_ErrCode ret;
95    ret = OH_CryptoSymKeyGenerator_Create("AES128", &genCtx);
96    if (ret != CRYPTO_SUCCESS) {
97        goto end;
98    }
99    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
100    if (ret != CRYPTO_SUCCESS) {
101        goto end;
102    }
103
104    // Set parameters.
105    ret = OH_CryptoSymCipherParams_Create(&params);
106    if (ret != CRYPTO_SUCCESS) {
107        goto end;
108    }
109    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivBlob);
110    if (ret != CRYPTO_SUCCESS) {
111        goto end;
112    }
113    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadBlob);
114    if (ret != CRYPTO_SUCCESS) {
115        goto end;
116    }
117    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagInit);
118    if (ret != CRYPTO_SUCCESS) {
119        goto end;
120    }
121
122    // Encrypt data.
123    ret = OH_CryptoSymCipher_Create("AES128|GCM|PKCS7", &encCtx);
124    if (ret != CRYPTO_SUCCESS) {
125        goto end;
126    }
127    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
128    if (ret != CRYPTO_SUCCESS) {
129        goto end;
130    }
131
132    for (int i = 0; i < cnt; i++) {
133        msgBlob.len = blockSize;
134        ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate);
135        if (ret != CRYPTO_SUCCESS) {
136            goto end;
137        }
138        msgBlob.data += blockSize;
139        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
140        cipherLen += outUpdate.len;
141    }
142    if (rem > 0) {
143        msgBlob.len = rem;
144        ret = OH_CryptoSymCipher_Update(encCtx, (Crypto_DataBlob *)&msgBlob, &outUpdate);
145        if (ret != CRYPTO_SUCCESS) {
146            goto end;
147        }
148        memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len);
149        cipherLen += outUpdate.len;
150    }
151    ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tag);
152    if (ret != CRYPTO_SUCCESS) {
153        goto end;
154    }
155
156    // Decrypt data.
157    cipherBlob = {.data = reinterpret_cast<uint8_t *>(cipherText), .len = (size_t)cipherLen};
158    msgBlob.data -= strlen(plainText) - rem;
159    msgBlob.len = strlen(plainText);
160    ret = OH_CryptoSymCipher_Create("AES128|GCM|PKCS7", &decCtx);
161    if (ret != CRYPTO_SUCCESS) {
162        goto end;
163    }
164    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tag);
165    if (ret != CRYPTO_SUCCESS) {
166        goto end;
167    }
168    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
169    if (ret != CRYPTO_SUCCESS) {
170        goto end;
171    }
172    ret = OH_CryptoSymCipher_Final(decCtx, &cipherBlob, &decUpdate);
173    if (ret != CRYPTO_SUCCESS) {
174        goto end;
175    }
176
177end:
178    OH_CryptoSymCipherParams_Destroy(params);
179    OH_CryptoSymCipher_Destroy(encCtx);
180    OH_CryptoSymCipher_Destroy(decCtx);
181    OH_CryptoSymKeyGenerator_Destroy(genCtx);
182    OH_CryptoSymKey_Destroy(keyCtx);
183    OH_Crypto_FreeDataBlob(&outUpdate);
184    OH_Crypto_FreeDataBlob(&tag);
185    OH_Crypto_FreeDataBlob(&decUpdate);
186    return ret;
187}
188```
189