我有一個帶有自簽名證書的openssl X509結構。我需要從這個結構中得到一個PEM格式的C++字符串。
以下內容應該適合您。它顯示了您需要執行的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-----
來源
2014-03-22 04:46:07
jww
我看着x509.c代碼如你所說,發現他們使用PEM_write_bio_X509函數寫PEM格式的數據。然後我使用BIO_read將這些數據讀入char數組。謝謝。 – jobless