我有一个带有自签名证书的 openssl X509 结构。我需要从此结构中获取 PEM 格式的 C++ 字符串。我需要使用哪些 openssl API 来实现此目的?
我尝试按照 https://www.codeblog.org/gonzui/markup/openssl-0.9.8a/demos/x509/mkcert.c 的示例程序进行操作.该程序展示了一种将 PEM 格式的证书写入文件的方法。如果没有其他方法,我可以将此文件的内容读入 C++ 字符串。
最佳答案
I have a openssl X509 structure with a self signed certificate. I need to get a PEM formatted C++ string from this structure.
以下应该适合您。它显示了您需要执行此操作的 API(没有填充证书字段的代码)。
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::unique_ptr;
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
using X509_ptr = std::unique_ptr<X509, decltype(&::X509_free)>;
using BIO_MEM_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
int main(int argc, char* argv[])
{
int rc = 0;
unsigned long err = 0;
X509_ptr x509(X509_new(), ::X509_free);
/* ... */
BIO_MEM_ptr bio(BIO_new(BIO_s_mem()), ::BIO_free);
rc = PEM_write_bio_X509(bio.get(), x509.get());
err = ERR_get_error();
if (rc != 1)
{
cerr << "PEM_write_bio_X509 failed, error " << err << ", ";
cerr << std::hex << "0x" << err;
exit(1);
}
BUF_MEM *mem = NULL;
BIO_get_mem_ptr(bio.get(), &mem);
err = ERR_get_error();
if (!mem || !mem->data || !mem->length)
{
cerr << "BIO_get_mem_ptr failed, error " << err << ", ";
cerr << std::hex << "0x" << err;
exit(2);
}
string pem(mem->data, mem->length);
cout << pem << endl;
return 0;
}
编译如下:
g++ -g -O -std=c++11 x509.cpp -o x509.exe \
-I/usr/local/ssl/include \
/usr/local/ssl/lib/libcrypto.a -ldl
典型的输出是:
$ ./x509.exe
-----BEGIN CERTIFICATE-----
MCYwHAIBADADBgEAMAAwBB8AHwAwADAIMAMGAQADAQAwAwYBAAMBAA==
-----END CERTIFICATE-----
关于c++ - 如何使用 openssl 将 PEM 编码的 X509 证书作为 C++ 字符串获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6877588/