c++ - 使用 QSslCertificate 在 Qt 中正确导入 pkcs12

标签 c++ qt pkcs#12

我想使用 QSslCertificate 导入私钥和证书。

QFile keyFile(QDir::currentPath()+ "/privatekey.pfx");
keyFile.open(QFile::ReadOnly);
QString password = "Password";
QSslKey key(keyFile.readAll(), QSsl::Rsa, QSsl::Der, QSsl::PrivateKey);
QFile certFile(QDir::currentPath()+ "/certificate.crt");
certFile.open(QFile::ReadOnly);
QSslCertificate certificate;
QList<QSslCertificate> importedCerts = QSslCertificate::fromData(certFile.readAll());

bool imported = QSslCertificate::importPkcs12(&keyFile, &key, &certificate, &importedCerts);
QSslConfiguration config = QSslConfiguration();
config.setCaCertificates(importedCerts);
config.setLocalCertificate(certificate);
config.setPrivateKey(key);
config.setProtocol(QSsl::SecureProtocols);
config.setPeerVerifyMode(QSslSocket::VerifyPeer);

根据文档,我以 pfx 格式加载私钥。在 Debug模式下,每次我从 QSslCertificate::importPkcs12 得到错误结果。可能是什么原因?

最佳答案

您使用的 API 完全错误。该方法的 key 和证书指针参数是out参数,您不应该预先向它们填充数据。

假设您有一个包含主证书的 PKCS#12 文件,要获取私钥、证书以及主证书(可选)的证书链,正确的用法是:

QFile pfxFile(QDir::currentPath()+ "/privatekey.pfx");
bool isOpen = pfxFile.open(QFile::ReadOnly);
// you should verify the file is open here!

// all default contructed, as they are filled by the importPkcs12 method
QSslKey key;
QSslCertificate certificate;
QList<QSslCertificate> certChain;

// now import into those three
bool imported = QSslCertificate::importPkcs12(&pfxFile, &key, &certificate, &certChain, password);
// imported should be true now, continue creating the ssl config as you did before

关于c++ - 使用 QSslCertificate 在 Qt 中正确导入 pkcs12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784293/

相关文章:

c++ - 通过引用为 boost::shared_ptr 创建别名

c++ - C++ 中奇怪的 getline 行为

c++ - 打印链接列表

c++ - 从 QML 连接到 C++ 信号

c++ - 动态 Qt 字符串翻译

c++ - 如何在 QwtPlot 上设置固定数量的刻度

android - 如何在 Android 上使用 .p12 证书?

java - 如何将证书文件添加/转换为 pkcs12 文件

c++ - 在虚拟机上运行的 C++ 多线程文件读取问题

java - 由于错误 : java. security.KeyStoreException:不支持 TrustedCertEntry,使用 Java API 创建 pkcs12 失败