问题
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