how to convert the Certificate String into X509 structure.?

假装没事ソ 提交于 2019-11-30 08:53:05

You can use this OpenSSL code snippet to load the certificate when provided as a string input:

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

const unsigned char *data = 
    "-----BEGIN CERTIFICATE-----\n"
    "MIIExDCCA6ygAwIBAgIJAK0JmDc/YXWsMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n"
    /*...*/
    "gRQT0OIU5vXzsmhjqKoZ+dBlh1FpSOX2\n"
    "-----END CERTIFICATE-----";

BIO *bio;
X509 *certificate;

bio = BIO_new(BIO_s_mem());
BIO_puts(bio, data);
certificate = PEM_read_bio_X509(bio, NULL, NULL, NULL);

Hope this helps.

Balamurugan

Below code is not complete code to run. It gives what the API and how to use them:

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

const unsigned char data[] = 
     "-----BEGIN CERTIFICATE-----\n"
"MIIExDCCA6ygAwIBAgIJAK0JmDc/YXWsMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n"
/*...*/
"gRQT0OIU5vXzsmhjqKoZ+dBlh1FpSOX2\n"
"-----END CERTIFICATE-----";

BIO *bio;
X509 *certificate;
bio = BIO_new(BIO_s_mem());            
// create BIO structure which deals with memory
lTemp= BIO_write(lBio, (const void*)data, sizeof(data));  
// Note Bio write and BIO puts do the exact thing difference is u need to give 
// the size of input data to copy in the Bio write. (Safe and best use bio write) 
// Check lTemp should be equal to the size of data or number of characters
// in the data u want to copy....

// these values are defined in my code not in the library
if (iFileType == DERFORMAT)
{
    certificate = d2i_X509_bio(bio, NULL);            
    // this line will decode the DER format certificate
    // and convert that into X509 formatted certificate.
}
else if (iFileType == PEMFORMAT) 
{
    certificate = PEM_read_bio_X509(bio, NULL, 0, NULL);        
    // this line will decode the PEM certificate
    // and convert that into X509 formatted certificate.
}        
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!