使用 QSslCertificate 在 Qt 中正确导入 pkcs12
Import properly pkcs12 in Qt using QSslCertificate
我想使用 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 格式的私钥。在调试模式下,每次我从 QSslCertificate::importPkcs12 得到错误的结果。可能是什么原因?
您使用的 API 完全错误。该方法的密钥和证书指针参数是 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
我想使用 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 格式的私钥。在调试模式下,每次我从 QSslCertificate::importPkcs12 得到错误的结果。可能是什么原因?
您使用的 API 完全错误。该方法的密钥和证书指针参数是 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