代码基于GMSSL库实现
1、sm4加密
int sm4EvpEncrypt(unsigned char *key, unsigned char *in, int inl, unsigned char *out)
{
unsigned char iv[SMS4_IV_LENGTH];
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
EVP_EncryptInit_ex(ctx, EVP_sms4_ecb(), NULL, key, iv);//设置ecb加密模式
EVP_CIPHER_CTX_set_padding(ctx, 0);//设置不填充
int len = 0;
int outl = 0;
EVP_EncryptUpdate(ctx, out, &outl, in, inl);
len = outl;
EVP_EncryptFinal_ex(ctx, out+len, &outl);
len += outl;
EVP_CIPHER_CTX_cleanup(ctx);
return len;
}
2、SM4解密
int sm4EvpDecrypt(unsigned char *key, unsigned char *in, int inl, unsigned char *out)
{
unsigned char iv[SMS4_IV_LENGTH];
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
EVP_DecryptInit_ex(ctx, EVP_sms4_ecb(), NULL, key, iv);//设置ecb加密模式
EVP_CIPHER_CTX_set_padding(ctx, 0);//设置不填充
int len = 0;
int outl = 0;
EVP_DecryptUpdate(ctx, out, &outl, in, inl);
len = outl;
EVP_DecryptFinal_ex(ctx, out+len, &outl);
len += outl;
EVP_CIPHER_CTX_cleanup(ctx);
return len;
}