openssl C语言 sm2 密钥转成PEM_STRING_ECPRIVATEKEY
openssl库提供了将EVP_PKEY类型的SM2密钥转换为PEM_STRING_ECPRIVATEKEY格式的函数,可以使用以下代码实现:
#include <openssl/pem.h>
int sm2_key_to_pem(EVP_PKEY *key, char **out_pem)
{
BIO *bio = BIO_new(BIO_s_mem());
if (!bio) {
return -1;
}
if (!PEM_write_bio_ECPrivateKey(bio, EVP_PKEY_get0_EC_KEY(key), NULL, NULL, 0, NULL, NULL)) {
BIO_free(bio);
return -1;
}
size_t len = BIO_pending(bio);
*out_pem = (char *)malloc(len + 1);
if (!*out_pem) {
BIO_free(bio);
return -1;
}
int ret = BIO_read(bio, *out_pem, len);
if (ret < 0) {
free(*out_pem);
BIO_free(bio);
return -1;
}
(*out_pem)[len] = '\0';
BIO_free(bio);
return 0;
}
在上述代码中,我们使用了BIO对象进行内存中的PEM格式输出,最后将结果存储在out_pem指向的缓冲区中,需要注意的是,最后一定要记得调用free()函数释放内存。
使用示例:
EVP_PKEY *key = ...; // 获得SM2密钥
char *pem = NULL;
if (sm2_key_to_pem(key, &pem) == 0) {
printf("%s\n", pem);
free(pem);
}
原文地址: https://www.cveoy.top/t/topic/bSBJ 著作权归作者所有。请勿转载和采集!