SM2加密c语言实现
时间: 2023-12-01 15:42:29 浏览: 312
以下是基于GMSSL实现SM2加密的C语言代码示例:
```c
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include <openssl/sm2.h>
int sm2_encrypt(unsigned char *in, size_t inlen, unsigned char *out, size_t *outlen, EC_KEY *ec_key)
{
int ret = 0;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL) {
printf("EVP_PKEY_new failed\n");
return -1;
}
if (EVP_PKEY_set1_EC_KEY(pkey, ec_key) != 1) {
printf("EVP_PKEY_set1_EC_KEY failed\n");
EVP_PKEY_free(pkey);
return -1;
}
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey, NULL);
if (ctx == NULL) {
printf("EVP_PKEY_CTX_new failed\n");
EVP_PKEY_free(pkey);
return -1;
}
if (EVP_PKEY_encrypt_init(ctx) <= 0) {
printf("EVP_PKEY_encrypt_init failed\n");
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return -1;
}
if (EVP_PKEY_CTX_set_ec_padding(ctx, SM2_DEFAULT_PADDING) <= 0) {
printf("EVP_PKEY_CTX_set_ec_padding failed\n");
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return -1;
}
if (EVP_PKEY_encrypt(ctx, out, outlen, in, inlen) <= 0) {
printf("EVP_PKEY_encrypt failed\n");
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return -1;
}
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return ret;
}
```
其中,`in`为待加密的数据,`inlen`为待加密数据的长度,`out`为加密后的数据,`outlen`为加密后数据的长度,`ec_key`为SM2算法的密钥对。
阅读全文