X509证书转换为字符串

X509证书转换为字符串

本文介绍了OpenSSL X509证书转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码(略作简化)从X509结构获取证书字符串.基本上是PEM_write_bio_X509函数.

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

结果正确地类似于

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

有什么办法(以后不用我自己手动进行转换)直接从OpenSSL作为一个没有标题行的行字符串来获取它?像这样:

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

推荐答案

有两个OpenSSL函数可以帮助您实现这一目标

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

PEM_read_bio()可以读取您的PEM格式证书文件(或与此相关的任何PEM格式的文​​件)并将其拆分为其标头和数据.

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.

随后您会对在data指针中获得的内容感兴趣,该指针以长字符串编码为base64. EVP_EncodeBlock()可以通过将其内容提供给您作为其第二个参数.

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.

您的代码的大致概述:

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

这篇关于OpenSSL X509证书转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 11:31