Setting Padding for SM4-ECB and SM4-CBC Encryption and Decryption
The SM4 algorithm uses the PKCS7 padding mode by default. To set another padding mode, call the Init interface twice. In the first call, do not pass the key and IV (pass NULL). Then, call the EVP_CIPHER_CTX_ctrl interface to set the padding mode. Finally, call the Init interface again to pass the key and IV. The following is a code example:
EVP_DecryptInit_ex(dctx, EVP_sm4_cbc(), g_engine, NULL, NULL); // First Init. No data is passed.
ASSERT(EVP_CIPHER_CTX_ctrl(dctx, EVP_CTRL_BLOCK_PADDING_MODE, EVP_PADDING_PKCS7, NULL) == 1,"set dctx padding success"); // Set padding.
EVP_DecryptInit_ex(dctx, EVP_sm4_cbc(), g_engine, g_key16, g_iv16);
EVP_DecryptUpdate(dctx, dt, &outl, ct, 32);
totl = outl;
EVP_DecryptFinal_ex(dctx, dt + totl, &outl);
totl += outl;
EVP_CIPHER_CTX_free(dctx);
Note: PKCS7 padding will add a full block when the input data is already a multiple of the block size. Allocate memory in advance.
Parent topic: FAQs