We know that using the openssl command line to extract the public key and private key factor from the pem of the national secret sm2 is as follows:
openssl ec -in sm2_test_priv.pem -text -noout
Extract private key from private key pemopenssl ec -pubin -in sm2_test_pub.pem -text -noout
Extract public key from public key pem
Taking private key extraction as an example, how to implement the above part in C language? The following is a reference example written for everyone:
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
int main() {
const char *filename = "test_priv.pem"; // 替换为你的PEM文件路径
// 打开PEM文件
FILE *file = fopen(filename, "r");
if (!file) {
perror("Error opening file");
return 1;
}
// 从PEM文件中读取RSA私钥
RSA *rsa_private_key = PEM_read_RSAPrivateKey(file, NULL, NULL, NULL);
fclose(file);
if (!rsa_private_key) {
ERR_print_errors_fp(stderr);
return 1;
}
// 输出私钥信息
printf("RSA Private Key:\n");
RSA_print_fp(stdout, rsa_private_key, 0);
// 释放私钥内存
RSA_free(rsa_private_key);
return 0;
}
Compile command:gcc main.c -o x -lssl -lcrypto