• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Encryption and Decryption with an SM4 Symmetric Key (CBC 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-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.
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|CBC|PKCS7'** to create a **Cipher** instance for encryption. The key type is **SM4_128**, block cipher mode is **CBC**, 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 CBC 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   - If a small amount of data is to be encrypted, you can use **OH_CryptoSymCipher_Final()** immediately after **OH_CryptoSymCipher_Init()**.
32   - 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.
33
346. Call [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_final) to obtain the encrypted data.
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. 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.
40
41**Decryption**
42
431. Call [OH_CryptoSymCipher_Create](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_create) with the string parameter **'SM4_128|CBC|PKCS7'** to create a **Cipher** instance for decryption. The key type is **SM4_128**, block cipher mode is **CBC**, and the padding mode is **PKCS7**.
44
452. 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 CBC mode.
46
473. Call [OH_CryptoSymCipher_Update](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_update) to update data (in ciphertext).
48
494. Call [OH_CryptoSymCipher_Final](../../reference/apis-crypto-architecture-kit/capi-crypto-sym-cipher-h.md#oh_cryptosymcipher_final) to obtain the decrypted data.
50
51```c++
52#include "CryptoArchitectureKit/crypto_common.h"
53#include "CryptoArchitectureKit/crypto_sym_cipher.h"
54#include <string.h>
55
56static OH_Crypto_ErrCode doTestSm4Cbc()
57{
58    OH_CryptoSymKeyGenerator *genCtx = nullptr;
59    OH_CryptoSymCipher *encCtx = nullptr;
60    OH_CryptoSymCipher *decCtx = nullptr;
61    OH_CryptoSymKey *keyCtx = nullptr;
62    OH_CryptoSymCipherParams *params = nullptr;
63    Crypto_DataBlob outUpdate = {.data = nullptr, .len = 0};
64    Crypto_DataBlob decUpdate = {.data = nullptr, .len = 0};
65
66    char *plainText = const_cast<char *>("this is test!");
67    Crypto_DataBlob msgBlob = {.data = (uint8_t *)(plainText), .len = strlen(plainText)};
68    uint8_t iv[16] = {1, 2, 4, 12, 3, 4, 2, 3, 3, 2, 0, 4, 3, 1, 0, 10}; // iv is generated from an array of secure random numbers.
69    Crypto_DataBlob ivBlob = {.data = iv, .len = sizeof(iv)};
70    // Generate a symmetric key.
71    OH_Crypto_ErrCode ret;
72    ret = OH_CryptoSymKeyGenerator_Create("SM4_128", &genCtx);
73    if (ret != CRYPTO_SUCCESS) {
74        goto end;
75    }
76    ret = OH_CryptoSymKeyGenerator_Generate(genCtx, &keyCtx);
77    if (ret != CRYPTO_SUCCESS) {
78        goto end;
79    }
80
81    // Set parameters.
82    ret = OH_CryptoSymCipherParams_Create(&params);
83    if (ret != CRYPTO_SUCCESS) {
84        goto end;
85    }
86    ret = OH_CryptoSymCipherParams_SetParam(params, CRYPTO_IV_DATABLOB, &ivBlob);
87    if (ret != CRYPTO_SUCCESS) {
88        goto end;
89    }
90
91    // Encrypt data.
92    ret = OH_CryptoSymCipher_Create("SM4_128|CBC|PKCS7", &encCtx);
93    if (ret != CRYPTO_SUCCESS) {
94        goto end;
95    }
96    ret = OH_CryptoSymCipher_Init(encCtx, CRYPTO_ENCRYPT_MODE, keyCtx, params);
97    if (ret != CRYPTO_SUCCESS) {
98        goto end;
99    }
100    ret = OH_CryptoSymCipher_Final(encCtx, &msgBlob, &outUpdate);
101    if (ret != CRYPTO_SUCCESS) {
102        goto end;
103    }
104
105    // Decrypt data.
106    ret = OH_CryptoSymCipher_Create("SM4_128|CBC|PKCS7", &decCtx);
107    if (ret != CRYPTO_SUCCESS) {
108        goto end;
109    }
110    ret = OH_CryptoSymCipher_Init(decCtx, CRYPTO_DECRYPT_MODE, keyCtx, params);
111    if (ret != CRYPTO_SUCCESS) {
112        goto end;
113    }
114    ret = OH_CryptoSymCipher_Final(decCtx, &outUpdate, &decUpdate);
115    if (ret != CRYPTO_SUCCESS) {
116        goto end;
117    }
118
119    // Release the resources.
120end:
121    OH_CryptoSymCipherParams_Destroy(params);
122    OH_CryptoSymCipher_Destroy(encCtx);
123    OH_CryptoSymCipher_Destroy(decCtx);
124    OH_CryptoSymKeyGenerator_Destroy(genCtx);
125    OH_CryptoSymKey_Destroy(keyCtx);
126    OH_Crypto_FreeDataBlob(&outUpdate);
127    OH_Crypto_FreeDataBlob(&decUpdate);
128    return ret;
129}
130```
131