基于openssl库的sm4对称加密算法
问题:解密后多出的填充字符暂未想到怎么去除。
sm4C语言实现源码
gcc sm4.c mm.c -lssl -lcrypto
运算结果:
sm4算法文件
//sm4.c
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <stdio.h>
#include <stdlib.h>
#include "sm4.h"
static void sm4_show_openssl_error(int8_t* title)
{
int8_t buf[1024];
ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
printf("%s: %s\n", title, buf);
}
static const EVP_CIPHER *sm4_get_mode(int8_t *mode)
{
switch (*mode) {
case '0':
return EVP_sm4_ecb();
case '1':
return EVP_sm4_cbc();
case '2':
return EVP_sm4_cfb128();
default:
return NULL;
}
}
static int32_t sm4_get_rand(uint8_t *out, uint32_t len)
{
BIGNUM *rnd;
uint8_t buf[32];
uint32_t idx;
rnd = BN_new();
if (NULL == rnd) {
return -1;
}
if (!BN_rand(rnd, 256, 1, 1)) {
return -1;
}
if (BN_bn2binpad(rnd, buf, 32) != 32) {
return -1;
}
BN_free(rnd);
show_hex("rand", buf, 32);
for (idx = 0; idx < len; idx