C语言实现:从sm2 PEM文件中提取公钥和私钥因子

我们知道使用openssl命令行从国密sm2的pem中提公钥私钥因子的命令行如下:

  • openssl ec -in sm2_test_priv.pem -text -noout 从私钥pem提取私钥
  • openssl ec -pubin -in sm2_test_pub.pem -text -noout 从公钥pem提取公钥

以私钥提取为例,那么以上部分,如何用C语言实现呢? 以下是为大家写的一个参考示例:

#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;
}

编译命令: gcc main.c -o x -lssl -lcrypto

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42135087/article/details/132465850