来源: chatGPT
#include <iostream>
#include <fstream>
#include <string>
#include <openssl/pem.h>
std::string readPEMFile(const std::string& filePath) {
std::string pemContent;
// 打开 PEM 文件
FILE* file = fopen(filePath.c_str(), "r");
if (!file) {
std::cerr << "Failed to open PEM file: " << filePath << std::endl;
return pemContent;
}
// 读取 PEM 文件内容
EVP_PKEY* pkey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!pkey) {
std::cerr << "Failed to read PEM file: " << filePath << std::endl;
fclose(file);
return pemContent;
}
// 将 PEM 文件内容转换为字符串
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
std::cerr << "Failed to create BIO." << std::endl;
fclose(file);
EVP_PKEY_free(pkey);
return pemContent;
}
if (PEM_write_bio_PrivateKey(bio, pkey, nullptr, nullptr, 0, nullptr, nullptr) != 1) {
std::cerr << "Failed to write PEM to BIO." << std::endl;
fclose(file);
EVP_PKEY_free(pkey);
BIO_free_all(bio);
return pemContent;
}
char* buffer;
long length = BIO_get_mem_data(bio, &buffer);
pemContent.assign(buffer, length);
// 清理资源
fclose(file);
EVP_PKEY_free(pkey);
BIO_free_all(bio);
return pemContent;
}
int main() {
std::string pemFilePath = "path/to/pem/file.pem";
std::string pemContent = readPEMFile(pemFilePath);
if (!pemContent.empty()) {
std::cout << "PEM content:\n" << pemContent << std::endl;
} else {
std::cerr << "Failed to read PEM file." << std::endl;
}
return 0;
}
编译:
g++ -o read_pem_file read_pem_file.cpp -lssl -lcrypto