Openssl X509证书从HexStream中解析

整体思路

hex 转换成字节流

然后从字节流中进行解析

You have access to the raw certificate in memory.

In the case that you have access to the raw encoding of the certificate in memory, you can parse it as follows. This is useful if you have stored raw certificates in a database or similar data store.

cpp 复制代码
#include 
#include 
#include 

const unsigned char *data = ... ;
size_t len = ... ;

X509 *cert = d2i_X509(NULL, &data, len);
if (!cert) {
	fprintf(stderr, "unable to parse certificate in memory\n");
	return EXIT_FAILURE;
}

// any additional processing would go here..

X509_free(cert);
cpp 复制代码
std::string hex_str = "30820317308201ffa003020102021432e1f.....";

// hex -> binaryData
std::vector<uint8_t> binaryData;
for (size_t i = 0; i < hex_str.size(); i += 2) {
    unsigned int byte;
    sscanf(hex_str.substr(i, 2).c_str(), "%02X", &byte);
    binaryData.push_back(byte);
}
 // 将 char* 转换为 unsigned char*
const unsigned char* uchar_ptr = binaryData.data();

size_t len = binaryData.size();
X509 *cert  = d2i_X509(NULL,&uchar_ptr,len);

if (!cert) {
    printf("Failed to load certificate from bytes\n");
    return 1;
}

// 打印证书信息
X509_print_fp(stdout, cert);

// 释放资源
X509_free(cert);

使用CryptoPP 解析

使用 CryptoPP 库进行解析

cpp 复制代码
   std::string hex_str = "30820317308201ffa003020102021.....";

    std::string binaryData;
    CryptoPP::StringSource(hex_str, true,
                 new CryptoPP::HexDecoder(
                         new CryptoPP::StringSink(binaryData)
                 )
    );


    CryptoPP::ByteQueue googleq, thawteq, googletbs, thawtespki;
    CryptoPP::SecByteBlock certSignature;

    googleq.Put((const CryptoPP::byte*)binaryData.data(), binaryData.size());

    CryptoPP::X509Certificate cert;

    cert.Load(googleq);

    // 获取公钥
    const CryptoPP::PublicKey& publicKey = cert.GetSubjectPublicKey();

    // 如果你确定证书的类型是 RSA,你可以将 PublicKey 强制转换为 RSA 公钥
    const CryptoPP::RSA::PublicKey& rsaPublicKey = dynamic_cast<const RSA::PublicKey&>(publicKey);
    // 获取 RSA 模数
    const CryptoPP::Integer& modulus = rsaPublicKey.GetModulus();


// 打印公钥信息
    std::cout << "Public Key: " <<rsaPublicKey.GetPublicExponent()<< std::endl;
    // 打印 RSA 模数
    std::cout << "RSA Modulus: " << modulus<< std::endl;
相关推荐
Larry_Yanan1 小时前
QML学习笔记(三十四)QML的GroupBox、RadioButton
c++·笔记·qt·学习·ui
程序员老舅2 小时前
干货|腾讯 Linux C/C++ 后端开发岗面试
linux·c语言·c++·编程·大厂面试题
程序员Aries2 小时前
自定义网络协议与序列化/反序列化
linux·网络·c++·网络协议·程序人生
Pafey2 小时前
MFC中一个类的成员变量值自动被篡改:多重继承带来的问题
c++·mfc
hsjkdhs2 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
阳光雨滴3 小时前
使用wpf用户控件编程落石效果动画
c++·wpf
小贾要学习4 小时前
【数据结构】C++实现红黑树
数据结构·c++
ajassi20004 小时前
开源 C++ QT QML 开发(十七)进程--LocalSocket
c++·qt·开源
微露清风4 小时前
系统性学习C++-第五讲-内存管理
java·c++·学习
星夜钢琴手6 小时前
推荐的 Visual Studio 2026 Insider C++ 程序项目属性配置
c++·visual studio