How to load a .p12 key into the QSslKey object?



  • Hi,

    I'm trying to build a https link using QNetworkAccessManager. I tried to load my certificate and private key into the configuration object of class QSslConfiguration. The certificate was loaded successfully, but I got some problem with the private key. The key file could be opened properly, but when I tried to construct a QSslKey object using the loaded QByteArray, the key is always not valid. Here are the codes:

        QSslConfiguration config;
        QFile certFile(QDir::currentPath() + QString("/sslCert/testcert.cer"));
        bool openOk = certFile.open(QIODevice::ReadWrite);
        qDebug() << "cert open ok = " << openOk; //ok
        QSslCertificate sslCert(certFile.readAll(), QSsl::Der);
        qDebug()<<"cert valid = " << !sslCert.isNull(); //not null
        config.setLocalCertificate(sslCert);
    
        QFile keyFile(QDir::currentPath() + QString("/sslCert/testkey.p12"));
        openOk = keyFile.open(QIODevice::ReadWrite);
        qDebug() << "key open ok = " << openOk; //ok
        qDebug() << keyFile.readAll(); //not empty
        QSslKey sslKey(keyFile.readAll(), QSsl::Rsa, QSsl::Der, QSsl::PrivateKey, "123456");
        qDebug()<< "key valid = " << !sslKey.isNull(); //**is null**
        config.setPrivateKey(sslKey);
    

    Is there anything wrong?

    P.S. I'm using Qt 5.5.1 under Ubuntu 14.04. The certificate and key were generated by keytool.They were all tested and could be imported properly into firefox and chrome.



  • AFAIK .p12 is not a private Key.
    It contains both keys and certs .

    You must use QSslKey to load a private key,



  • @luca yes you are right. :)
    Just now I've tried to export the private key from the .p12 file with the openssl API. This key could be constructed into QSslKey object now. Thanks a lot.
    But to configure in such a way is a little bit too complicated. Is there any class or method I can use, so that I can directly import the .p12 file into the QSslConfiguration object?



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.