#include "pch.h"
#include "CertificateManager.h"

namespace SSLClient {

CertificateManager::CertificateManager()
{
}

CertificateManager::~CertificateManager()
{
}

X509* CertificateManager::LoadCertificateFromMemory(const char* certPem)
{
	if (!certPem) {
		std::cerr << "[错误] 证书数据为空" << std::endl;
		return nullptr;
	}

	BIO* bio = BIO_new_mem_buf(certPem, -1);
	if (!bio) {
		PrintSSLError("创建BIO失败");
		return nullptr;
	}

	X509* cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
	BIO_free(bio);

	if (!cert) {
		PrintSSLError("读取证书失败");
	}

	return cert;
}

EVP_PKEY* CertificateManager::LoadPrivateKeyFromMemory(const char* keyPem, const char* password)
{
	if (!keyPem) {
		std::cerr << "[错误] 私钥数据为空" << std::endl;
		return nullptr;
	}

	BIO* bio = BIO_new_mem_buf(keyPem, -1);
	if (!bio) {
		PrintSSLError("创建BIO失败");
		return nullptr;
	}

	EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, (void*)password);
	BIO_free(bio);

	if (!pkey) {
		PrintSSLError("读取私钥失败");
	}

	return pkey;
}

void CertificateManager::PrintSSLError(const char* message)
{
	unsigned long err = ERR_get_error();
	if (err == 0) {
		std::cerr << "[错误] " << message << std::endl;
		return;
	}

	char errBuf[256];
	ERR_error_string_n(err, errBuf, sizeof(errBuf));
	std::cerr << "[错误] " << message << ": " << errBuf << std::endl;
}

} // namespace SSLClient
