使用 openssl 以编程方式提取 pem 证书信息

Posted

技术标签:

【中文标题】使用 openssl 以编程方式提取 pem 证书信息【英文标题】:Extract pem certificate information programmatically using openssl 【发布时间】:2011-09-24 10:47:52 【问题描述】:

使用 openssl 命令行可以以人类可读的模式提取 .pem 证书中包含的所有信息;那就是:

openssl x509 -noout -in <MyCertificate>.pem  -text

使用 openssl API 提取此信息的合适步骤是什么?

问候,

【问题讨论】:

感谢您提供 openssl 命令,我正在谷歌上搜索它并来到这里。 【参考方案1】:

X509_print_ex 系列函数就是您的答案。

#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/bio.h>

int main(int argc, char **argv)

    X509 *x509;
    BIO *i = BIO_new(BIO_s_file());
    BIO *o = BIO_new_fp(stdout,BIO_NOCLOSE);

    if((argc < 2) ||
       (BIO_read_filename(i, argv[1]) <= 0) ||
       ((x509 = PEM_read_bio_X509_AUX(i, NULL, NULL, NULL)) == NULL)) 
        return -1;
    

    X509_print_ex(o, x509, XN_FLAG_COMPAT, X509_FLAG_COMPAT);

【讨论】:

【参考方案2】:

作为与此问题相关的附加信息,如果拥有 DER 格式而不是 PEM 的证书;也可以使用以下代码以人类可读的模式提取信息:

//Assuming that the DER certificate binary information is stored in
//a byte array (unsigned char) called "pData" whose size is "lenData"
X509* x509;
BIO* input = BIO_new_mem_buf((void*)pData, lenData);
//d2i_X509_bio: Decodes the binary DER certificate
//and parses it to a X509 structure
x509 = d2i_X509_bio(input, NULL);
if (x509 == NULL)

   //Error in d2i_X509_bio

else

    //"certificateFile" is the full path file
    //where to store the certificate information
    //in a human readable mode (instead of stdout)
    FILE* fd = fopen(certificateFile, "w+");
    BIO* output = BIO_new_fp(fd, BIO_NOCLOSE);
    X509_print_ex(output, x509, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
    fclose(fd);
    BIO_free_all(output);

BIO_free_all(input);

【讨论】:

以上是关于使用 openssl 以编程方式提取 pem 证书信息的主要内容,如果未能解决你的问题,请参考以下文章

使用 OpenSSL 以编程方式创建 X509 证书

以编程方式从 PEM 获取 KeyStore

使用openssl命令从.p12文件中提取证书和私钥。

pem 格式证书 怎么使用openssl

openssl生成.pem证书

如何以 .pem 格式保存证书中的公钥