Extract pem certificate information programmatically using openssl

浪子不回头ぞ 提交于 2019-11-29 18:13:59

问题


Using the openssl command line is possible to extract, in a human readable mode, all the information contained in a .pem certificate; that is:

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

What are the suitable steps in order to extract this information using the openssl API?

Regards,


回答1:


The X509_print_ex family of functions is your answer.

#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:


As additional information related to this question, in case of having a certificate with the DER format instead of PEM; it is also possible to extract the information in a human readable mode using the following code:

//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);


来源:https://stackoverflow.com/questions/6509189/extract-pem-certificate-information-programmatically-using-openssl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!