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;
相关推荐
听风若依10 分钟前
C++模板初阶
c++·算法
纪念 2291 小时前
C++ 算法(模拟)
开发语言·c++·算法
zwc32104320551 小时前
Day 2:图像内存、数据类型与stride
c++·人工智能·opencv·算法·计算机视觉
道尔柯南2 小时前
C++ 内存管理详解:从 malloc/free 到 new/delete
c++·面试
東隅已逝,桑榆非晚2 小时前
AVL数实现
c++·笔记·学习·算法
思想觉悟2 小时前
SEAndroid实战
android·linux·c++
.YM.Z2 小时前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
思想觉悟2 小时前
Aosp开发磨刀石之ADB速查
android·c++
小此方2 小时前
C++ 工程组件与基础设施(三)详解RPC服务的概念与安装,图片介绍Brpc服务器和客户端的搭建过程
服务器·c++·rpc
qq_406981033 小时前
什么是顶层 const什么是底层const
开发语言·c++