Qt QSslSocket“证书是自签名的,并且不受信任”

mr.*_*leo 5 c++ sockets qt qsslsocket server

我想用 QSslSocket 连接服务器,在服务器上我得到 soketSslError “证书是自签名的,并且不受信任”,但我不明白为什么会出现此错误。

第一步是使用 openssl 为服务器和客户端生成文件

$openssl req -new -newkey rsa:1024 -keyout ca.key -x509 -days 500 -out ca.crt
$openssl req -new -newkey rsa:1024 -keyout client01.key -out client01.csr
$openssl ca -config ca.config -in  client01.csr -out client01.crt -batch
Run Code Online (Sandbox Code Playgroud)

在C++服务器/客户端中

在服务器上:

启动服务器

if (listen(QHostAddress::Any,this->connectingPort)) {
        std::cout<<"Server start on port: "<<this->connectingPort<<std::endl;
        return true;
    } else {
        std::cout<<"Cant start server. "<<errorString().toStdString().c_str()<<std::endl;
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

传入连接

    QFile keyFile("ca.key");
    if (!keyFile.open(QIODevice::ReadOnly)) {
        delete this->sslSocket;
        qDebug()<<"Cant open file: "<<keyFile.fileName();
        return false;
    }
    QByteArray pasp ="qwerty";
    QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
    if (key.isNull()) {
        delete this->sslSocket;
        qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
        return false;
    }
    keyFile.close();

    this->sslSocket->setPrivateKey(key);
    this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);
    this->sslSocket->setLocalCertificate("ca.crt");
    this->sslSocket->startServerEncryption();
Run Code Online (Sandbox Code Playgroud)

在客户端:

this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);


QFile keyFile("client01.key");

if (!keyFile.open(QIODevice::ReadOnly)) {
    delete this->sslSocket;
    qDebug()<<"Cant open file: "<<keyFile.fileName();
    return ;
}
QByteArray pasp ="qwerty";
QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
if (key.isNull()) {
    delete this->sslSocket;
    qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
    return ;
}
keyFile.close();

this->sslSocket->setPrivateKey(key);

this->sslSocket->setLocalCertificate("client01.crt");

this->sslSocket->connectToHostEncrypted("192.168.0.10",1258);

if (!this->sslSocket->waitForEncrypted()) {
    qDebug()<<"error: "<<sslSocket->errorString();
}
Run Code Online (Sandbox Code Playgroud)

当我从客户端连接时出现服务器错误

soket ssl error
"The certificate is self-signed, and untrusted" 
"The certificate is self-signed, and untrusted" 
socketError:  QAbstractSocket::SocketError( 13 ) 
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?

更新:

Qt Creator 3.0.1 基于 Qt 5.2.1(GCC 4.8.2,64 位)

Mar*_*rco 3

我建议你在服务器上尝试一下:

QList<QSslCertificate> cert = QSslCertificate::fromPath(QLatin1String("your-certificate.pem"));
QSslError error(QSslError::SelfSignedCertificate, cert.at(0));
QList<QSslError> expectedSslErrors;
expectedSslErrors.append(error);

this->sslSocket.ignoreSslErrors(expectedSslErrors);
Run Code Online (Sandbox Code Playgroud)