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;
相关推荐
小欣加油7 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
星恒随风8 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
浪客灿心8 小时前
项目篇:模块设计与实现
数据库·c++
牛油果子哥q9 小时前
【C++ STL vector】C++ STL vector 终极精讲:动态数组底层原理、两倍扩容机制、迭代器失效、增删查改、性能剖析与工程避坑指南
开发语言·c++
为何创造硅基生物10 小时前
独占指针的创建std::make_unique 本身自带堆出现
c++
kyle~11 小时前
ROS 2 与 Isaac Sim 联合仿真(一)体系架构、环境选型与基础通信闭环
c++·机器人·nvidia·仿真·ros2
努力努力再努力wz11 小时前
【内存管理与高并发内存池系列】从 mmap 到 malloc:文件映射、匿名映射与 glibc 内存分配机制详解
linux·c语言·数据结构·数据库·c++·qt·链表
八解毒剂11 小时前
数据结构-平衡二叉树——对二叉搜索树的优化
数据结构·c++·算法
起床困难户57512 小时前
条款20:协助完成返回值优化
c++
啦啦啦啦啦zzzz12 小时前
算法总结(二分查找、双指针)
c++·算法