我正在实现使用TCP进行通信的客户端 - 服务器应用程序。我想使用SSL来提高安全性,但我需要使客户端甚至可以连接到具有自签名或“非常非常安全”证书的服务器。现在我创建了一些随机测试证书,我试图在我的本地机器上使用它(服务器和客户端都在那里运行,不能完成服务器主机解析,它只是localhost)。
我一直在客户端收到此错误:
Socket error: The host name did not match any of the valid hosts for this certificate
我试图通过使用此代码来抑制它:
// We don't care about self signed certificates
QList<QSslError> errors;
errors << QSslError(QSslError::SelfSignedCertificate);
errors << QSslError(QSslError::HostNameMismatch);
((QSslSocket*)this->socket)->ignoreSslErrors(errors);
((QSslSocket*)this->socket)->connectToHostEncrypted(this->hostname, this->port);
然而它不起作用,无论我在连接之前还是之后使用此代码,它仍然因为“不匹配”错误而失败。
如何告诉QSslSocket
“亲爱的套接字,如果证书是自签名的,或者与有效主机不匹配,我根本不在乎,请联系我”?
答案 0 :(得分:2)
所以,我明白了:
只有在类的构造函数中指定证书时,带参数的ignoreSslErrors
才有效。
另一种方法是调用ignoreSslErrors()
而不带参数。但是,需要从连接到信号sslErrors的Qt插槽调用此函数。它没有解释为什么它所要求的似乎没有任何其他方式。
文档:http://doc.qt.io/qt-5/qsslsocket.html#ignoreSslErrors-1
工作示例
void Program::OnSslHandshakeFailure(QList<QSslError> errors)
{
this->socket->ignoreSslErrors();
}
void Program::Connect()
{
connect(this->socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(OnSslHandshakeFailure(QList<QSslError>)));
this->socket->connectToHostEncrypted(this->hostname, this->port);
}