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_SetParams](../../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**Example** 55 56```c++ 57#include <string.h> 58#include "CryptoArchitectureKit/crypto_common.h" 59#include "CryptoArchitectureKit/crypto_sym_cipher.h" 60 61#define OH_CRYPTO_GCM_TAG_LEN 16 62static OH_Crypto_ErrCode doTestSm4GcmSeg() 63{ 64 OH_CryptoSymKeyGenerator *genCtx = nullptr; 65 OH_CryptoSymCipher *encCtx = nullptr; 66 OH_CryptoSymCipher *decCtx = nullptr; 67 OH_CryptoSymKey *keyCtx = nullptr; 68 OH_CryptoSymCipherParams *params = nullptr; 69 70 uint8_t plainText[] = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; 71 Crypto_DataBlob msgBlob = {.data = reinterpret_cast<uint8_t *>(plainText), .len = sizeof(plainText)}; 72 73 uint8_t aad[8] = {0}; 74 uint8_t tagArr[16] = {0}; 75 uint8_t iv[12] = {0}; 76 Crypto_DataBlob tag = {.data = nullptr, .len = 0}; 77 Crypto_DataBlob ivBlob = {.data = iv, .len = sizeof(iv)}; 78 Crypto_DataBlob aadBlob = {.data = aad, .len = sizeof(aad)}; 79 Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0}; 80 Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0}; 81 Crypto_DataBlob tagInit = {.data = tagArr, .len = sizeof(tagArr)}; 82 int32_t cipherLen = 0; 83 int blockSize = 20; 84 int32_t randomLen = sizeof(plainText); 85 int cnt = randomLen / blockSize; 86 int rem = randomLen % blockSize; 87 uint8_t cipherText[sizeof(plainText) + 16] = {0}; 88 Crypto_DataBlob cipherBlob = {.data = reinterpret_cast<uint8_t *>(cipherText), .len = (size_t)cipherLen}; 89 90 // Generate a key. 91 OH_Crypto_ErrCode ret; 92 ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx); 93 if (ret != CRYPTO_SUCCESS) { 94 goto end; 95 } 96 ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx); 97 if (ret != CRYPTO_SUCCESS) { 98 goto end; 99 } 100 101 // Set parameters. 102 ret = OH_CryptoSymCipherParams_Create(¶ms); 103 if (ret != CRYPTO_SUCCESS) { 104 goto end; 105 } 106 ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivBlob); 107 if (ret != CRYPTO_SUCCESS) { 108 goto end; 109 } 110 ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadBlob); 111 if (ret != CRYPTO_SUCCESS) { 112 goto end; 113 } 114 ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagInit); 115 if (ret != CRYPTO_SUCCESS) { 116 goto end; 117 } 118 119 // Encrypt data. 120 ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &encCtx); 121 if (ret != CRYPTO_SUCCESS) { 122 goto end; 123 } 124 ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params); 125 if (ret != CRYPTO_SUCCESS) { 126 goto end; 127 } 128 129 for (int i = 0; i < cnt; i++) { 130 msgBlob.len = blockSize; 131 ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate); 132 if (ret != CRYPTO_SUCCESS) { 133 goto end; 134 } 135 msgBlob.data += blockSize; 136 memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len); 137 cipherLen += outUpdate.len; 138 } 139 if (rem > 0) { 140 msgBlob.len = rem; 141 ret = OH_CryptoSymCipher_Update(encCtx, (Crypto_DataBlob *)&msgBlob, &outUpdate); 142 if (ret != CRYPTO_SUCCESS) { 143 goto end; 144 } 145 memcpy(&cipherText[cipherLen], outUpdate.data, outUpdate.len); 146 cipherLen += outUpdate.len; 147 } 148 cipherBlob.len = cipherLen; 149 ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tag); 150 if (ret != CRYPTO_SUCCESS) { 151 goto end; 152 } 153 154 // Decrypt data. 155 msgBlob.data -= sizeof(plainText) - rem; 156 msgBlob.len = sizeof(plainText); 157 ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &decCtx); 158 if (ret != CRYPTO_SUCCESS) { 159 goto end; 160 } 161 ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tag); 162 if (ret != CRYPTO_SUCCESS) { 163 goto end; 164 } 165 ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params); 166 if (ret != CRYPTO_SUCCESS) { 167 goto end; 168 } 169 ret = OH_CryptoSymCipher_Final(decCtx, &cipherBlob, &decUpdate); 170 if (ret != CRYPTO_SUCCESS) { 171 goto end; 172 } 173 if (memcmp(msgBlob.data, decUpdate.data, msgBlob.len) == 0) { 174 ret = (OH_Crypto_ErrCode)1234567; 175 } else { 176 ret = (OH_Crypto_ErrCode)456; 177 } 178end: 179 OH_CryptoSymCipherParams_Destroy(params); 180 OH_CryptoSymCipher_Destroy(encCtx); 181 OH_CryptoSymCipher_Destroy(decCtx); 182 OH_CryptoSymKeyGenerator_Destroy(genCtx); 183 OH_CryptoSymKey_Destroy(keyCtx); 184 OH_Crypto_FreeDataBlob(&outUpdate); 185 OH_Crypto_FreeDataBlob(&tag); 186 OH_Crypto_FreeDataBlob(&decUpdate); 187 return ret; 188} 189``` 190