通过openssl解析pfx私钥证书,qtc++实现


前言

因为我对证书理解不深,仅仅为了完成需求,所以很可能会有错误,希望大家批评指正

本次代码所使用的openssl版本为1.1.1u。

网上的资料其实并不少,但似乎都是老版本的了,我所使用的openssl版本为1.1.1,结构体已经不暴露出来了,所以实现了部分方法,可以分享一下。


一、openssl

我是使用qt5.12.12编译的,理论上qt5就行。

二、使用步骤

1.引入库

代码如下,需要在pro文件中链接库(跟demo中不一样,只是说需要链接这两个库):

LIBS += -lopenssl -lcrypto

2.使用

代码如下(示例):

Adapts::UKey::SW_DigitalCertificate tmpParser;
tmpParser.VerifyCertificate(pfxFile, "password"); //这个密码需要改成自己证书的密码

注意哦,GetIssuerName获取的是乱码,又涉及到了字符串编码的问题,本人才疏学浅尚未解决,如果路过的大佬知道为啥麻烦告诉小弟一下,感激不尽


在这里插入图片描述


3.证书解析

主要依靠PKCS12_parse获取X509结构体,并对其进行解析,demo代码放在链接中:
demo代码git地址

bool SW_DigitalCertificate::VerifyCertificate(const QString &certificateName, const QString &password)
{
    QFile certificateFile(certificateName);
    if(!certificateFile.exists()) {
        qDebug() << "certificate file is not exists";
        return false;
    }
    
    certificateFile.open(QIODevice::ReadOnly);
    QByteArray fileArr = certificateFile.readAll();
    char * context = fileArr.data();
    certificateFile.close();

    BIO * bio = BIO_new(BIO_s_mem());
    int rv = BIO_write(bio, context, fileArr.size());

    if(!bio || 0 == rv) {
        qDebug() << "BIO_write||BIO_new error";
        return false;
    }

    PKCS12 *p12 = NULL;
	p12 = d2i_PKCS12_bio(bio, &p12);

	EVP_PKEY* pkey = NULL;
	X509* x509 = NULL;
	STACK_OF(X509)* ca = NULL;

    bool returnRes = false;
    if (!PKCS12_parse(p12, password.toUtf8(), &pkey, &x509, &ca)) {
        qDebug() << "PKCS12_parse error";
        returnRes = false;
    }else{
        d_ptr->m_certificateNamePwdMap.insert(certificateName, password);
        //打印数据
        ShowCertificateInfo(x509);

        returnRes = true;
    }

    X509_free(x509);		
    sk_X509_pop_free(ca, X509_free);
    ca = NULL;	
    PKCS12_free(p12);
    p12 = NULL;

    return returnRes;
}

#include "digitalcertificateprivate.h"

#include <openssl/x509v3.h>

#include <QDateTime>
#include <QDebug>

QString Ada
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值