OpenSSL X509 certificate to string

无人久伴 提交于 2019-12-24 09:10:08

问题


I am using following code (simplified little bit) to get certificate string from X509 structure. Basically PEM_write_bio_X509 function.

X509 *certificate...
....
BIO *bio = BIO_new(BIO_s_mem()), BIO_vfree);
if (!bio || !PEM_write_bio_X509(bio, certificate)) {
    // error handling
}
size_t keylen = BIO_pending(bio);
unique_ptr<char[]> key(new char[keylen]);
int len = BIO_read(bio, key.get(), (int)keylen);
if (len <= 0) {
    // error handling
}
string result = string(key.get(), len);

The result is correctly something like

-----BEGIN CERTIFICATE-----
MIIFLTCCAxUCCQDrAnFYOmsVkzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJB
VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
-----END CERTIFICATE-----

Is there any way (without converting it manually myself later) to get it directly from OpenSSL as one line string without header lines? Something like:

MIIFLTCCAxUCCQDrAnFYOmsVkzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0

回答1:


There are two OpenSSL functions that can help you to achieve this

PEM_read_bio() can read your PEM-formatted certificate file (or any PEM-formatted file for that matter) and split it into its header and data.

You are subsequently interested in the contents obtained in the data pointer, encoded as base64 in a long string. EVP_EncodeBlock() can give you that by giving it those contents as its second parameter.

A rough outline of your code :

ret = PEM_read_bio(bio, &name, &header, &data, &len);
if (!ret) {
    // error
}

// Make sure b64block is allocated to contain at least
//     4*ceil(len/3) + 1 bytes
blockLen = EVP_EncodeBlock(b64block, data, len);
// b64block now contains the desired base64 in blockLen relevant bytes,
//     plus a null-character

// Don't forget to OPENSSL_free the name, header and data pointers


来源:https://stackoverflow.com/questions/51500960/openssl-x509-certificate-to-string

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