为什么我不能获得用户正在使用的证书的正确信息?

Why can not I get the right information about the certificate, which is used by the user?

本文关键字:证书 信息 不能 用户 为什么      更新时间:2023-10-16

这是两个完全不同的网站。他们有两个不同的ssl证书。下面描述的程序充当服务器。客户端是浏览器。当我访问为我的https服务器服务的不同站点时,我总是得到一个哈希值。

    #include <QCoreApplication>
    #include "server.h"
    int main(int argc, char *argv[]) {
        QCoreApplication a(argc, argv);
        Server h;
        return a.exec();
    }
    ///////////////////////////////////////
    #ifndef SERVER_H
    #define SERVER_H
    #include <QTcpServer>
    class Server : public QTcpServer {
        public:
        Server();
        void incomingConnection(int);
    };
    #endif // SERVER_H

    ///////////////////////////////////////////
    #include "server.h"
    #include <QSslSocket>
    #include <QSslCertificate>
    Server::Server() {
        if (!listen(QHostAddress::Any, 80)) {
            //error
        }
    }
    void Server::incomingConnection(int d) {
        QSslSocket * socket = new QSslSocket();
        if(socket->setSocketDescriptor(d)) {
            socket->setProtocol(QSsl::AnyProtocol);
            //always one hash. why?
            qDebug() << socket->peerCertificate().digest(QCryptographicHash::Sha1).toHex();
            QString c, k;
            c = "site.crt";
            k = "site.key";
            socket->setLocalCertificate(c);
            socket->setPrivateKey(k);
            socket->startServerEncryption();
            if(socket->waitForEncrypted()) {
                if(socket->waitForReadyRead()) {
                    socket->write(socket->readAll());
                    socket->waitForBytesWritten();
                    socket->disconnectFromHost();
                    if(socket->state() == QTcpSocket::UnconnectedState) {
                        socket->waitForDisconnected();
                    }
                    socket->close();
                    socket->deleteLater();
                }
                else {
                    delete socket;
                }
            }
            else {
                delete socket;
            }
        }
    }

来自Qt文档:

因为对端证书是在握手阶段设置的,所以是从连接的插槽安全访问对端证书sslErrors()信号或encrypted()信号

如果返回一个空证书,它可能意味着SSL握手失败,也可能意味着您所连接的主机没有证书,或者表示没有连接。

因此,您应该在本地插槽接收到QSslSocket::加密信号后尝试获取客户端证书。

你还应该注意,如果你的客户端没有证书,那么peerCertificate()将返回一个空值