0

我正在编写代理服务器,http 部分已准备好,但 https 有问题。我以这种方式创建了一个证书和私钥(据我所知,没有它将无法工作):

OpenSSL> req-x509-newkey rsa: 2048-keyout server.key-nodes-days 365-out server.csr

我做了一个简单的 QTcpServer,它将一个 socketDescriptor 传递给 newIncomingConnection() 上创建的对象。在我的对象的构造函数中,我做了:

    sock = new QSslSocket();
    connect (sock,SIGNAL(readyRead()),this,SLOT(onQuery()));
    connect(sock,SIGNAL(disconnected()),this,SLOT(deleteLater()));
    connect(sock,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError(QAbstractSocket::SocketError)));
    connect(sock,SIGNAL(sslErrors(QList<QSslError>)),this,SLOT(sltSslErrors(QList<QSslError>)));

...
Load key and cert
...
    sock->setProtocol(QSsl::AnyProtocol);
    QSslKey sslKey(key, QSsl::Rsa);
    QSslCertificate sslCert(cert);
    sock->setPrivateKey(sslKey);
    sock->setLocalCertificate(sslCert);
    sock->setSocketDescriptor(socketDesc);
    sock->startServerEncryption();
    if(!sock->waitForEncrypted(30000)) {
        qDebug()<<"wait for encrypted failed";
    }

在控制台中连接时,我看到“等待加密失败”并且套接字发出信号 error() 与 QAbstractSocket::SslHandshakeFailedError。您能否就如何无误地建立 ssl 连接提供建议?

4

1 回答 1

1

我相信你需要在调用and方法setSocketDescriptor之前调用。setPrivateKeysetLocalCertificate

下面是我用来创建一个HTTPS Server Socket扩展的代码QTcpServer

void SslServer::incomingConnection(qintptr socketDescriptor)
{
    QSslSocket *serverSocket = new QSslSocket;
    if (serverSocket->setSocketDescriptor(socketDescriptor)) {
        QFile keyFile(<sslKeyFileName>);
        if (!keyFile.open(QIODevice::ReadOnly)) {
            delete serverSocket;
            return;
        }
        QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
        if (key.isNull()) {
            delete serverSocket;
            return;
        }
        keyFile.close();
        serverSocket->setPrivateKey(key);
        // to prevent asking for client certificate.
        serverSocket->setPeerVerifyMode(QSslSocket::VerifyNone); 
        serverSocket->setLocalCertificate(<certificateFileName>);
        serverSocket->startServerEncryption();
        if (serverSocket->waitForEncrypted(3000)) {
            // this will emit a newConnection() signal
            addPendingConnection(serverSocket);
        } else {
            qDebug() << "Encryption Failed.";
            delete serverSocket;
        }
    } else {
        delete serverSocket;
    }
}
于 2013-12-24T06:51:55.960 回答