You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言调用OpenSSL读取PEM格式证书提取RSA公钥方法

C语言基于OpenSSL提取PEM证书RSA公钥实现

前置要求

  • 开发环境已安装OpenSSL 1.1.1及以上版本开发库
  • 编译时需要链接OpenSSL的crypto模块,示例编译命令:
    gcc cert_extract_rsa.c -o cert_extract_rsa -lcrypto

完整实现代码

#include <stdio.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/err.h>

int main() {
    // 初始化OpenSSL错误字符串与算法库
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    const char* cert_path = "ABCcert.pem";
    FILE* cert_fp = fopen(cert_path, "r");
    if (!cert_fp) {
        fprintf(stderr, "无法打开证书文件%s\n", cert_path);
        return 1;
    }

    // 读取PEM格式证书为X509结构体
    X509* cert = PEM_read_X509(cert_fp, NULL, NULL, NULL);
    fclose(cert_fp);
    if (!cert) {
        fprintf(stderr, "解析PEM证书失败,错误信息:\n");
        ERR_print_errors_fp(stderr);
        return 1;
    }

    // 从证书中提取公钥
    EVP_PKEY* pubkey = X509_get_pubkey(cert);
    if (!pubkey) {
        fprintf(stderr, "从证书中提取公钥失败,错误信息:\n");
        ERR_print_errors_fp(stderr);
        X509_free(cert);
        return 1;
    }

    // 校验公钥类型是否为RSA
    if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_RSA) {
        fprintf(stderr, "证书内公钥不是RSA类型,无法提取\n");
        EVP_PKEY_free(pubkey);
        X509_free(cert);
        return 1;
    }

    // 获取RSA公钥结构体,可直接用于后续加密操作
    RSA* rsa_pubkey = EVP_PKEY_get1_RSA(pubkey);
    if (!rsa_pubkey) {
        fprintf(stderr, "获取RSA公钥结构体失败,错误信息:\n");
        ERR_print_errors_fp(stderr);
        EVP_PKEY_free(pubkey);
        X509_free(cert);
        return 1;
    }

    /*
    后续可直接使用rsa_pubkey调用RSA_public_encrypt完成加密操作
    示例加密调用参考:
    int enc_len = RSA_public_encrypt(plaintext_len, plaintext_buf, ciphertext_buf, rsa_pubkey, RSA_PKCS1_OAEP_PADDING);
    */
    printf("RSA公钥提取成功,密钥长度:%d bit\n", RSA_bits(rsa_pubkey));

    // 按顺序释放所有OpenSSL对象,避免内存泄漏
    RSA_free(rsa_pubkey);
    EVP_PKEY_free(pubkey);
    X509_free(cert);
    EVP_cleanup();
    ERR_free_strings();

    return 0;
}

关键注意事项

  • 代码中拿到的rsa_pubkey是可直接用于加密的RSA公钥对象,不需要额外做格式转换
  • 如果需要将公钥导出为单独的PEM格式公钥文件,可在获取rsa_pubkey后调用PEM_write_RSAPublicKey(输出文件指针, rsa_pubkey)完成写入
  • 加密操作优先使用RSA_PKCS1_OAEP_PADDING填充模式,安全性优于传统PKCS#1 v1.5填充
  • 所有OpenSSL申请的结构体必须手动调用对应*_free接口释放,否则会造成内存泄漏
  • OpenSSL 3.0及以上版本依然兼容上述API,不需要做额外适配

运行代码前请确认ABCcert.pem文件放在程序运行的工作目录下,否则请替换cert_path变量为证书的绝对路径。

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.08 16:15:17