openssl C语言DER SM2私钥转为PKCS#8 的PEM格式
以下是将DER编码的SM2私钥转换为PKCS#8 PEM格式的示例代码:
#include <openssl/pem.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
int main()
{
// 读取DER编码的SM2私钥
FILE* fp = fopen("sm2.key", "rb");
if (!fp) {
printf("failed to open file\n");
return 1;
}
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char* buf = malloc(fsize);
if (!buf) {
printf("failed to allocate memory\n");
return 1;
}
fread(buf, fsize, 1, fp);
fclose(fp);
// 将DER编码的SM2私钥转为EVP_PKEY
EVP_PKEY* pkey = EVP_PKEY_new();
if (!pkey) {
printf("failed to create EVP_PKEY\n");
return 1;
}
EC_KEY* ec_key = EC_KEY_new();
if (!ec_key) {
printf("failed to create EC_KEY\n");
return 1;
}
EC_GROUP* ec_group = EC_GROUP_new_by_curve_name(NID_sm2);
if (!ec_group) {
printf("failed to create EC_GROUP\n");
return 1;
}
const unsigned char* p = buf;
ec_key = d2i_ECPrivateKey(&ec_key, &p, fsize);
if (!ec_key) {
printf("failed to parse ECPrivateKey\n");
return 1;
}
if (!EC_KEY_set_group(ec_key, ec_group)) {
printf("failed to set EC_KEY group\n");
return 1;
}
if (!EVP_PKEY_assign_EC_KEY(pkey, ec_key)) {
printf("failed to assign EVP_PKEY\n");
return 1;
}
// 将EVP_PKEY转为PKCS#8 PEM格式
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
printf("failed to create BIO\n");
return 1;
}
if (!PEM_write_bio_PKCS8PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL)) {
printf("failed to write PKCS8PrivateKey\n");
return 1;
}
// 输出PKCS#8 PEM格式私钥
BUF_MEM* mem = NULL;
BIO_get_mem_ptr(bio, &mem);
printf("%.*s", (int)mem->length, mem->data);
// 释放资源
free(buf);
EVP_PKEY_free(pkey);
BIO_free_all(bio);
return 0;
}
其中,sm2.key为DER编码的SM2私钥文件。运行后,将输出PKCS#8 PEM格式的私钥。
原文地址: https://www.cveoy.top/t/topic/bSAD 著作权归作者所有。请勿转载和采集!