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;
相关推荐
AI+程序员在路上40 分钟前
XML介绍及常用c及c++库
xml·c语言·c++
guoguo05241 小时前
vs2019及以后版本cmd指定编译环境文件的路径
c++
软行1 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
代码AC不AC2 小时前
【C++】STL简介
c++·stl简介
unityのkiven2 小时前
C++中的虚表和虚表指针的原理和示例
开发语言·c++
火山灿火山3 小时前
【简单模拟实现list】
c++
芯眼3 小时前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
汉克老师4 小时前
GESP2025年3月认证C++二级( 第三部分编程题(1)等差矩阵)
c++·算法·矩阵·gesp二级·gesp2级
joker D8885 小时前
【C++】深入理解 unordered 容器、布隆过滤器与分布式一致性哈希
c++·分布式·哈希算法
野曙6 小时前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大