• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Encryption and Decryption with an SM4 Symmetric Key (GCM Mode) (C/C++)
2
3<!--Kit: Crypto Architecture Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @zxz--3-->
6<!--Designer: @lanming-->
7<!--Tester: @PAFT-->
8<!--Adviser: @zengyawen-->
9
10For details about the algorithm specifications, see [SM4](crypto-sym-encrypt-decrypt-spec.md#sm4).
11
12## Adding the Dynamic Library in the CMake Script
13```txt
14target_link_libraries(entry PUBLIC libohcrypto.so)
15```
16
17**Encryption**
18
191. Call [OH_CryptoSymKeyGenerator_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-key-h.md#oh_cryptosymkeygenerator_create) and [OH_CryptoSymKeyGenerator_Generate](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-key-h.md#oh_cryptosymkeygenerator_generate) to generate a symmetric key (**OH_CryptoSymKey**) with the key algorithm being SM4 and the key length being 128 bits.
20
21   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.
22
232. Call [OH_CryptoSymCipher_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_create) with the string parameter **'SM4_128|GCM|PKCS7'** to create a **Cipher** instance for encryption. The key type is **SM4_128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**.
24
253. Call [OH_CryptoSymCipherParams_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipherparams_create) to create a parameter object and call [OH_CryptoSymCipherParams_SetParam](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipherparams_setparam) to set encryption parameters.
26
274. Call [OH_CryptoSymCipher_Init](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.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.
28
295. Call [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_update) to update data (in plaintext).
30
31   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.
32
33   - If a small amount of data is to be encrypted, you can use **OH_CryptoSymCipher_Final()** immediately after **OH_CryptoSymCipher_Init()**.
34   - 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](crypto-sm4-sym-encrypt-decrypt-gcm-by-segment-ndk.md).
35
366. Call [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_final) to obtain the encrypted data.
37   - If data has been passed in by **OH_CryptoSymCipher_Update()**, pass in **null** in the **data** parameter of **OH_CryptoSymCipher_Final**.
38   - The output of **OH_CryptoSymCipher_Final** may be **null**. To avoid exceptions, always check whether the result is **null** before accessing specific data.
39
407. Call [OH_CryptoSymCipherParams_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipherparams_create) to create a **Params** instance, and call [OH_CryptoSymCipherParams_SetParam](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.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.
41
428. Call [OH_CryptoSymKeyGenerator_Destroy](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-key-h.md#oh_cryptosymkeygenerator_destroy), [OH_CryptoSymCipher_Destroy](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_destroy), and [OH_CryptoSymCipherParams_Destroy](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipherparams_destroy) to destroy the objects.
43
44**Decryption**
45
461. Call [OH_CryptoSymCipher_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_create) with the string parameter **'SM4_128|GCM|PKCS7'** to create a **Cipher** instance for decryption. The key type is **SM4_128**, block cipher mode is **GCM**, and the padding mode is **PKCS7**.
47
482. Call [OH_CryptoSymCipher_Init](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_init) to initialize the **Cipher** instance. Specifically, set **mode** to **CRYPTO_DECRYPT_MODE**, and specify the decryption key (**OH_CryptoSymKey**) and the decryption parameter instance (**OH_CryptoSymCipherParams**) corresponding to the GCM mode.
49
503. Call [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_update) to update data (in ciphertext).
51
524. Call [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_final) to obtain the decrypted data.
53
54```c++
55#include "CryptoArchitectureKit/crypto_common.h"
56#include "CryptoArchitectureKit/crypto_sym_cipher.h"
57#include <string.h>
58
59static OH_Crypto_ErrCode doTestSm4Gcm()
60{
61    OH_CryptoSymKeyGenerator *genCtx = nullptr;
62    OH_CryptoSymCipher *encCtx = nullptr;
63    OH_CryptoSymCipher *decCtx = nullptr;
64    OH_CryptoSymKey *keyCtx = nullptr;
65    OH_CryptoSymCipherParams *params = nullptr;
66
67    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
68    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
69
70    uint8_t aad[8] = {1, 2, 3, 4, 5, 6, 7, 8};
71    uint8_t tag[16] = {0};
72    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.
73    Crypto_DataBlob ivData = {.data = iv, .len = sizeof(iv)};
74    Crypto_DataBlob aadData = {.data = aad, .len = sizeof(aad)};
75    Crypto_DataBlob tagData = {.data = tag, .len = sizeof(tag)};
76    Crypto_DataBlob tagOutPut = {.data = nullptr, .len = 0};
77    char *plainText = const_cast<char *>("this is test!");
78    Crypto_DataBlob msgBlob = {.data = (uint8_t *)(plainText), .len = strlen(plainText)};
79    // Generate a symmetric key.
80    OH_Crypto_ErrCode ret;
81    ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx);
82    if (ret != CRYPTO_SUCCESS) {
83        goto end;
84    }
85    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
86    if (ret != CRYPTO_SUCCESS) {
87        goto end;
88    }
89
90    // Set parameters.
91    ret = OH_CryptoSymCipherParams_Create(&params);
92    if (ret != CRYPTO_SUCCESS) {
93        goto end;
94    }
95    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivData);
96    if (ret != CRYPTO_SUCCESS) {
97        goto end;
98    }
99    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_AAD_DATABLOB, &aadData);
100    if (ret != CRYPTO_SUCCESS) {
101        goto end;
102    }
103    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagData);
104    if (ret != CRYPTO_SUCCESS) {
105        goto end;
106    }
107
108    // Encrypt the message.
109    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &encCtx);
110    if (ret != CRYPTO_SUCCESS) {
111        goto end;
112    }
113    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
114    if (ret != CRYPTO_SUCCESS) {
115        goto end;
116    }
117    ret = OH_CryptoSymCipher_Update(encCtx, &msgBlob, &outUpdate);
118    if (ret != CRYPTO_SUCCESS) {
119        goto end;
120    }
121    ret = OH_CryptoSymCipher_Final(encCtx, nullptr, &tagOutPut);
122    if (ret != CRYPTO_SUCCESS) {
123        goto end;
124    }
125
126    // Decrypt the message.
127    ret = OH_CryptoSymCipher_Create("SM4_128|GCM|PKCS7", &decCtx);
128    if (ret != CRYPTO_SUCCESS) {
129        goto end;
130    }
131    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_TAG_DATABLOB, &tagOutPut);
132    if (ret != CRYPTO_SUCCESS) {
133        goto end;
134    }
135    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
136    if (ret != CRYPTO_SUCCESS) {
137        goto end;
138    }
139    ret = OH_CryptoSymCipher_Final(decCtx, &outUpdate, &decUpdate);
140    if (ret != CRYPTO_SUCCESS) {
141        goto end;
142    }
143
144    // Release the resources.
145end:
146    OH_CryptoSymCipherParams_Destroy(params);
147    OH_CryptoSymCipher_Destroy(encCtx);
148    OH_CryptoSymCipher_Destroy(decCtx);
149    OH_CryptoSymKeyGenerator_Destroy(genCtx);
150    OH_CryptoSymKey_Destroy(keyCtx);
151    OH_Crypto_FreeDataBlob(&outUpdate);
152    OH_Crypto_FreeDataBlob(&decUpdate);
153    OH_Crypto_FreeDataBlob(&tagOutPut);
154    return ret;
155}
156```
157