QSslSocket 类

QSslSocket 类为客户端和服务器两者提供 SSL (安全套接字层) 加密套接字。 更多...

头: #include <QSslSocket>
CMake: find_package(Qt6 REQUIRED COMPONENTS Network)
target_link_libraries(mytarget PRIVATE Qt6::Network)
qmake: QT += network
继承: QTcpSocket

注意: 此类的所有函数 可重入 .

公共类型

enum PeerVerifyMode { VerifyNone, QueryPeer, VerifyPeer, AutoVerifyPeer }
enum SslMode { UnencryptedMode, SslClientMode, SslServerMode }

公共函数

QSslSocket (QObject * parent = nullptr)
virtual ~QSslSocket ()
void connectToHostEncrypted (const QString & hostName , quint16 port , QIODeviceBase::OpenMode mode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)
void connectToHostEncrypted (const QString & hostName , quint16 port , const QString & sslPeerName , QIODeviceBase::OpenMode mode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)
void continueInterruptedHandshake ()
qint64 encryptedBytesAvailable () const
qint64 encryptedBytesToWrite () const
void ignoreSslErrors (const QList<QSslError> & errors )
bool isEncrypted () const
QSslCertificate localCertificate () const
QList<QSslCertificate> localCertificateChain () const
QSslSocket::SslMode mode () const
QList<QOcspResponse> ocspResponses () const
QSslCertificate peerCertificate () const
QList<QSslCertificate> peerCertificateChain () const
int peerVerifyDepth () const
QSslSocket::PeerVerifyMode peerVerifyMode () const
QString peerVerifyName () const
QSslKey privateKey () const
QSsl::SslProtocol protocol () const
QSslCipher sessionCipher () const
QSsl::SslProtocol sessionProtocol () const
void setLocalCertificate (const QSslCertificate & certificate )
void setLocalCertificate (const QString & path , QSsl::EncodingFormat format = QSsl::Pem)
void setLocalCertificateChain (const QList<QSslCertificate> & localChain )
void setPeerVerifyDepth (int depth )
void setPeerVerifyMode (QSslSocket::PeerVerifyMode mode )
void setPeerVerifyName (const QString & hostName )
void setPrivateKey (const QSslKey & key )
void setPrivateKey (const QString & fileName , QSsl::KeyAlgorithm algorithm = QSsl::Rsa, QSsl::EncodingFormat format = QSsl::Pem, const QByteArray & passPhrase = QByteArray())
void setProtocol (QSsl::SslProtocol protocol )
void setSslConfiguration (const QSslConfiguration & configuration )
QSslConfiguration sslConfiguration () const
QList<QSslError> sslHandshakeErrors () const
bool waitForEncrypted (int msecs = 30000)

重实现公共函数

virtual bool atEnd () const override
virtual qint64 bytesAvailable () const override
virtual qint64 bytesToWrite () const override
virtual bool canReadLine () const override
virtual void close () override
virtual void resume () override
virtual void setReadBufferSize (qint64 size ) override
virtual bool setSocketDescriptor (qintptr socketDescriptor , QAbstractSocket::SocketState state = ConnectedState, QIODeviceBase::OpenMode openMode = ReadWrite) override
virtual void setSocketOption (QAbstractSocket::SocketOption option , const QVariant & value ) override
virtual QVariant socketOption (QAbstractSocket::SocketOption option ) override
virtual bool waitForBytesWritten (int msecs = 30000) override
virtual bool waitForConnected (int msecs = 30000) override
virtual bool waitForDisconnected (int msecs = 30000) override
virtual bool waitForReadyRead (int msecs = 30000) override

公共槽

void ignoreSslErrors ()
void startClientEncryption ()
void startServerEncryption ()

信号

void alertReceived (QSsl::AlertLevel level , QSsl::AlertType type , const QString & description )
void alertSent (QSsl::AlertLevel level , QSsl::AlertType type , const QString & description )
void encrypted ()
void encryptedBytesWritten (qint64 written )
void handshakeInterruptedOnError (const QSslError & error )
void modeChanged (QSslSocket::SslMode mode )
void newSessionTicketReceived ()
void peerVerifyError (const QSslError & error )
void preSharedKeyAuthenticationRequired (QSslPreSharedKeyAuthenticator * authenticator )
void sslErrors (const QList<QSslError> & errors )

静态公共成员

QString activeBackend ()
QList<QString> availableBackends ()
QList<QSsl::ImplementedClass> implementedClasses (const QString & backendName = {})
bool isClassImplemented (QSsl::ImplementedClass cl , const QString & backendName = {})
bool isFeatureSupported (QSsl::SupportedFeature ft , const QString & backendName = {})
bool isProtocolSupported (QSsl::SslProtocol protocol , const QString & backendName = {})
bool setActiveBackend (const QString & backendName )
long sslLibraryBuildVersionNumber ()
QString sslLibraryBuildVersionString ()
long sslLibraryVersionNumber ()
QString sslLibraryVersionString ()
QList<QSsl::SupportedFeature> supportedFeatures (const QString & backendName = {})
QList<QSsl::SslProtocol> supportedProtocols (const QString & backendName = {})
bool supportsSsl ()

重实现保护函数

virtual qint64 readData (char * data , qint64 maxlen ) override
virtual qint64 skipData (qint64 maxSize ) override
virtual qint64 writeData (const char * data , qint64 len ) override
enum class AlertLevel { Warning, Fatal, Unknown }
enum class AlertType { CloseNotify, UnexpectedMessage, BadRecordMac, RecordOverflow, DecompressionFailure, …, UnknownAlertMessage }
enum class ImplementedClass { Key, Certificate, Socket, DiffieHellman, EllipticCurve, …, DtlsCookie }
enum class SupportedFeature { CertificateVerification, ClientSideAlpn, ServerSideAlpn, Ocsp, Psk, …, Alerts }

详细描述

QSslSocket establishes a secure, encrypted TCP connection you can use for transmitting encrypted data. It can operate in both client and server mode, and it supports modern TLS protocols, including TLS 1.3. By default, QSslSocket uses only TLS protocols which are considered to be secure ( QSsl::SecureProtocols ), but you can change the TLS protocol by calling setProtocol () 只要在握手开始之前这样做。

SSL encryption operates on top of the existing TCP stream after the socket enters the ConnectedState. There are two simple ways to establish a secure connection using QSslSocket: With an immediate SSL handshake, or with a delayed SSL handshake occurring after the connection has been established in unencrypted mode.

使用 QSslSocket 的最常见方式是构造对象并启动安全连接通过调用 connectToHostEncrypted ()。此方法立即启动 SSL 握手,一旦连接已建立。

QSslSocket *socket = new QSslSocket(this);
connect(socket, &QSslSocket::encrypted, this, &Receiver::ready);
socket->connectToHostEncrypted("imap.example.com", 993);
					

就像纯 QTcpSocket , QSslSocket enters the HostLookupState, ConnectingState, and finally the ConnectedState, if the connection is successful. The handshake then starts automatically, and if it succeeds, the encrypted () 信号被发射以指示套接字已进入加密状态且准备使用。

注意,之后可以立即把数据写入套接字,当返回从 connectToHostEncrypted () (即:之前的 encrypted () 信号被发射)。数据先在 QSslSocket 中队列直到 encrypted () 信号被发射。

An example of using the delayed SSL handshake to secure an existing connection is the case where an SSL server secures an incoming connection. Suppose you create an SSL server class as a subclass of QTcpServer . You would override QTcpServer::incomingConnection () with something like the example below, which first constructs an instance of QSslSocket and then calls setSocketDescriptor () to set the new socket's descriptor to the existing one passed in. It then initiates the SSL handshake by calling startServerEncryption ().

void SslServer::incomingConnection(qintptr socketDescriptor)
{
    QSslSocket *serverSocket = new QSslSocket;
    if (serverSocket->setSocketDescriptor(socketDescriptor)) {
        addPendingConnection(serverSocket);
        connect(serverSocket, &QSslSocket::encrypted, this, &SslServer::ready);
        serverSocket->startServerEncryption();
    } else {
        delete serverSocket;
    }
}
					

If an error occurs, QSslSocket emits the sslErrors () signal. In this case, if no action is taken to ignore the error(s), the connection is dropped. To continue, despite the occurrence of an error, you can call ignoreSslErrors (), either from within this slot after the error occurs, or any time after construction of the QSslSocket and before the connection is attempted. This will allow QSslSocket to ignore the errors it encounters when establishing the identity of the peer. Ignoring errors during an SSL handshake should be used with caution, since a fundamental characteristic of secure connections is that they should be established with a successful handshake.

一旦被加密,使用 QSslSocket 作为常规 QTcpSocket 。当 readyRead () 被发射,可以调用 read (), canReadLine () 和 readLine (),或 getChar () to read decrypted data from QSslSocket's internal buffer, and you can call write () 或 putChar () to write data back to the peer. QSslSocket will automatically encrypt the written data for you, and emit encryptedBytesWritten () once the data has been written to the peer.

As a convenience, QSslSocket supports QTcpSocket 's blocking functions waitForConnected (), waitForReadyRead (), waitForBytesWritten (),和 waitForDisconnected (). It also provides waitForEncrypted (), which will block the calling thread until an encrypted connection has been established.

QSslSocket socket;
socket.connectToHostEncrypted("http.example.com", 443);
if (!socket.waitForEncrypted()) {
    qDebug() << socket.errorString();
    return false;
}
socket.write("GET / HTTP/1.0\r\n\r\n");
while (socket.waitForReadyRead())
    qDebug() << socket.readAll().data();
					

QSslSocket provides an extensive, easy-to-use API for handling cryptographic ciphers, private keys, and local, peer, and Certification Authority (CA) certificates. It also provides an API for handling errors that occur during the handshake phase.

还可以定制下列特征:

To extend the list of default CA certificates used by the SSL sockets during the SSL handshake you must update the default configuration, as in the snippet below:

QList<QSslCertificate> certificates = getCertificates();
QSslConfiguration configuration = QSslConfiguration::defaultConfiguration();
configuration.addCaCertificates(certificates);
QSslConfiguration::setDefaultConfiguration(configuration);
					

注意: If available, root certificates on Unix (excluding macOS) will be loaded on demand from the standard certificate directories. If you do not want to load root certificates on demand, you need to call either QSslConfiguration::defaultConfiguration ().setCaCertificates() before the first SSL handshake is made in your application (for example, via passing QSslSocket::systemCaCertificates() to it), or call QSslConfiguration::defaultConfiguration ()::setCaCertificates() on your QSslSocket instance prior to the SSL handshake.

For more information about ciphers and certificates, refer to QSslCipher and QSslCertificate .

This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit ( http://www.openssl.org/ ).

注意: Be aware of the difference between the bytesWritten () signal and the encryptedBytesWritten () signal. For a QTcpSocket , bytesWritten () will get emitted as soon as data has been written to the TCP socket. For a QSslSocket, bytesWritten () will get emitted when the data is being encrypted and encryptedBytesWritten () will get emitted as soon as data has been written to the TCP socket.

另请参阅 QSslCertificate , QSslCipher ,和 QSslError .

成员类型文档编制

enum QSslSocket:: PeerVerifyMode

描述对等验证模式为 QSslSocket . The default mode is AutoVerifyPeer, which selects an appropriate mode depending on the socket's QSocket::SslMode.

常量 描述
QSslSocket::VerifyNone 0 QSslSocket will not request a certificate from the peer. You can set this mode if you are not interested in the identity of the other side of the connection. The connection will still be encrypted, and your socket will still send its local certificate to the peer if it's requested.
QSslSocket::QueryPeer 1 QSslSocket will request a certificate from the peer, but does not require this certificate to be valid. This is useful when you want to display peer certificate details to the user without affecting the actual SSL handshake. This mode is the default for servers. Note: In Schannel this value acts the same as VerifyNone.
QSslSocket::VerifyPeer 2 QSslSocket will request a certificate from the peer during the SSL handshake phase, and requires that this certificate is valid. On failure, QSslSocket 将发射 QSslSocket::sslErrors () signal. This mode is the default for clients.
QSslSocket::AutoVerifyPeer 3 QSslSocket will automatically use QueryPeer for server sockets and VerifyPeer for client sockets.

另请参阅 QSslSocket::peerVerifyMode ().

enum QSslSocket:: SslMode

描述可用连接模式为 QSslSocket .

常量 描述
QSslSocket::UnencryptedMode 0 The socket is unencrypted. Its behavior is identical to QTcpSocket .
QSslSocket::SslClientMode 1 The socket is a client-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted ()).
QSslSocket::SslServerMode 2 The socket is a server-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted ()).

成员函数文档编制

[explicit] QSslSocket:: QSslSocket ( QObject * parent = nullptr)

构造 QSslSocket 对象。 parent 会被传递给 QObject 的构造函数。新套接字的 cipher suite is set to the one returned by the static method defaultCiphers().

[virtual noexcept] QSslSocket:: ~QSslSocket ()

销毁 QSslSocket .

[static, since 6.1] QString QSslSocket:: activeBackend ()

Returns the name of the backend that QSslSocket and related classes use. If the active backend was not set explicitly, this function returns the name of a default backend that QSslSocket selects implicitly from the list of available backends.

注意: When selecting a default backend implicitly, QSslSocket prefers the OpenSSL backend if available.

该函数在 Qt 6.1 引入。

另请参阅 setActiveBackend () 和 availableBackends ().

[signal] void QSslSocket:: alertReceived ( QSsl::AlertLevel level , QSsl::AlertType type , const QString & description )

QSslSocket emits this signal if an alert message was received from a peer. level tells if the alert was fatal or it was a warning. type is the code explaining why the alert was sent. When a textual description of the alert message is available, it is supplied in description .

注意: The signal is mostly for informational and debugging purposes and does not require any handling in the application. If the alert was fatal, underlying backend will handle it and close the connection.

注意: 并非所有后端都支持此功能。

另请参阅 alertSent (), QSsl::AlertLevel ,和 QSsl::AlertType .

[signal] void QSslSocket:: alertSent ( QSsl::AlertLevel level , QSsl::AlertType type , const QString & description )

QSslSocket emits this signal if an alert message was sent to a peer. level describes if it was a warning or a fatal error. type gives the code of the alert message. When a textual description of the alert message is available, it is supplied in description .

注意: This signal is mostly informational and can be used for debugging purposes, normally it does not require any actions from the application.

注意: 并非所有后端都支持此功能。

另请参阅 alertReceived (), QSsl::AlertLevel ,和 QSsl::AlertType .

[override virtual] bool QSslSocket:: atEnd () const

重实现: QIODevice::atEnd() const .

[static, since 6.1] QList < QString > QSslSocket:: availableBackends ()

Returns the names of the currently available backends. These names are in lower case, e.g. "openssl", "securetransport", "schannel" (similar to the already existing feature names for TLS backends in Qt).

该函数在 Qt 6.1 引入。

另请参阅 activeBackend ().

[override virtual] qint64 QSslSocket:: bytesAvailable () const

重实现: QAbstractSocket::bytesAvailable() const .

Returns the number of decrypted bytes that are immediately available for reading.

[override virtual] qint64 QSslSocket:: bytesToWrite () const

重实现: QAbstractSocket::bytesToWrite() const .

Returns the number of unencrypted bytes that are waiting to be encrypted and written to the network.

[override virtual] bool QSslSocket:: canReadLine () const

重实现: QIODevice::canReadLine() const .

返回 true if you can read one while line (terminated by a single ASCII '\n' character) of decrypted characters; otherwise, false is returned.

[override virtual] void QSslSocket:: close ()

重实现: QAbstractSocket::close ().

void QSslSocket:: connectToHostEncrypted (const QString & hostName , quint16 port , QIODeviceBase::OpenMode mode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)

启动加密连接到设备 hostName on port ,使用 mode 作为 OpenMode 。这相当于调用 connectToHost () 以建立连接,紧随其后调用 startClientEncryption ()。 protocol 参数可以用于指定要使用哪种网络协议 (如 IPv4 或 IPv6)。

QSslSocket first enters the HostLookupState. Then, after entering either the event loop or one of the waitFor...() functions, it enters the ConnectingState, emits connected (),然后初启 SSL 客户端握手。每次状态改变时, QSslSocket 发射信号 stateChanged ().

在初启 SSL (安全套接字层) 客户端握手后,若无法建立对等方身份,信号 sslErrors () is emitted. If you want to ignore the errors and continue connecting, you must call ignoreSslErrors (), either from inside a slot function connected to the sslErrors () signal, or prior to entering encrypted mode. If ignoreSslErrors () is not called, the connection is dropped, signal disconnected () is emitted, and QSslSocket returns to the UnconnectedState.

若 SSL (安全套接字层) 握手成功, QSslSocket 发射 encrypted ().

QSslSocket socket;
connect(&socket, &QSslSocket::encrypted, receiver, &Receiver::socketEncrypted);
socket.connectToHostEncrypted("imap", 993);
socket->write("1 CAPABILITY\r\n");
					

注意: The example above shows that text can be written to the socket immediately after requesting the encrypted connection, before the encrypted () signal has been emitted. In such cases, the text is queued in the object and written to the socket after the connection is established and the encrypted () 信号已发射。

默认为 mode is ReadWrite .

若想要创建 QSslSocket on the server side of a connection, you should instead call startServerEncryption () upon receiving the incoming connection through QTcpServer .

另请参阅 connectToHost (), startClientEncryption (), waitForConnected (),和 waitForEncrypted ().

void QSslSocket:: connectToHostEncrypted (const QString & hostName , quint16 port , const QString & sslPeerName , QIODeviceBase::OpenMode mode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)

这是重载函数。

In addition to the original behaviour of connectToHostEncrypted, this overloaded method enables the usage of a different hostname ( sslPeerName ) for the certificate validation instead of the one used for the TCP connection ( hostName ).

另请参阅 connectToHostEncrypted ().

[since 6.0] void QSslSocket:: continueInterruptedHandshake ()

If an application wants to conclude a handshake even after receiving handshakeInterruptedOnError () signal, it must call this function. This call must be done from a slot function attached to the signal. The signal-slot connection must be direct.

该函数在 Qt 6.0 引入。

另请参阅 handshakeInterruptedOnError () 和 QSslConfiguration::setHandshakeMustInterruptOnError ().

[signal] void QSslSocket:: encrypted ()

此信号被发射当 QSslSocket 进入加密模式。在发射此信号后, QSslSocket::isEncrypted () 将返回 true,且套接字的所有进一步传输都会被加密。

另请参阅 QSslSocket::connectToHostEncrypted () 和 QSslSocket::isEncrypted ().

qint64 QSslSocket:: encryptedBytesAvailable () const

Returns the number of encrypted bytes that are awaiting decryption. Normally, this function will return 0 because QSslSocket decrypts its incoming data as soon as it can.

qint64 QSslSocket:: encryptedBytesToWrite () const

Returns the number of encrypted bytes that are waiting to be written to the network.

[signal] void QSslSocket:: encryptedBytesWritten ( qint64 written )

此信号被发射当 QSslSocket writes its encrypted data to the network. The written parameter contains the number of bytes that were successfully written.

另请参阅 QIODevice::bytesWritten ().

[signal] void QSslSocket:: handshakeInterruptedOnError (const QSslError & error )

QSslSocket emits this signal if a certificate verification error was found and if early error reporting was enabled in QSslConfiguration . An application is expected to inspect the error and decide if it wants to continue the handshake, or abort it and send an alert message to the peer. The signal-slot connection must be direct.

另请参阅 continueInterruptedHandshake (), sslErrors (),和 QSslConfiguration::setHandshakeMustInterruptOnError ().

[slot] void QSslSocket:: ignoreSslErrors ()

此槽告诉 QSslSocket 去忽略错误在 QSslSocket 的握手阶段并继续连接。若想要继续连接即使在握手阶段发生错误,必须调用此槽,或从连接槽到 sslErrors (),或在握手阶段之前。若在响应出错或握手之前不调用此槽,连接将被丢弃当 sslErrors () 信号已发射。

If there are no errors during the SSL handshake phase (i.e., the identity of the peer is established with no problems), QSslSocket will not emit the sslErrors () signal, and it is unnecessary to call this function.

警告: 确保始终让用户审查报告的错误通过 sslErrors () 信号,且才调用此方法 (当用户确认后继续进行是 OK 的)。若存在意外错误,连接应该被中止。不审查实际错误就调用此方法,很可能会给应用程序带来安全风险。小心使用!

另请参阅 sslErrors ().

void QSslSocket:: ignoreSslErrors (const QList < QSslError > & errors )

这是重载函数。

此方法告诉 QSslSocket 仅忽略的错误给出于 errors .

注意: Because most SSL errors are associated with a certificate, for most of them you must set the expected certificate this SSL error is related to. If, for instance, you want to connect to a server that uses a self-signed certificate, consider the following snippet:

QList<QSslCertificate> cert = QSslCertificate::fromPath("server-certificate.pem"_L1);
QSslError error(QSslError::SelfSignedCertificate, cert.at(0));
QList<QSslError> expectedSslErrors;
expectedSslErrors.append(error);
QSslSocket socket;
socket.ignoreSslErrors(expectedSslErrors);
socket.connectToHostEncrypted("server.tld", 443);
					

多次调用此函数将替换先前调用传入错误列表。可以清零想要忽略的错误列表通过采用空列表调用此函数。

另请参阅 sslErrors () 和 sslHandshakeErrors ().

[static, since 6.1] QList < QSsl::ImplementedClass > QSslSocket:: implementedClasses (const QString & backendName = {})

This function returns backend-specific classes implemented by the backend named backendName . An empty backendName is understood as a query about the currently active backend.

该函数在 Qt 6.1 引入。

另请参阅 QSsl::ImplementedClass , activeBackend (),和 isClassImplemented ().

[static, since 6.1] bool QSslSocket:: isClassImplemented ( QSsl::ImplementedClass cl , const QString & backendName = {})

Returns true if a class cl is implemented by the backend named backendName . An empty backendName is understood as a query about the currently active backend.

该函数在 Qt 6.1 引入。

另请参阅 implementedClasses ().

bool QSslSocket:: isEncrypted () const

返回 true 若套接字被加密;否则,false 被返回。

加密套接字加密的所有数据的写入是通过调用 write () 或 putChar () 在将数据写入网络之前,并以数据形式解密从网络收到的所有传入数据,先于调用 read (), readLine () 或 getChar ().

QSslSocket 发射 encrypted () 当它进入加密模式时。

可以调用 sessionCipher () 以查找用于加密和解密数据的加密密码。

另请参阅 mode ().

[static, since 6.1] bool QSslSocket:: isFeatureSupported ( QSsl::SupportedFeature ft , const QString & backendName = {})

Returns true if a feature ft is supported by a backend named backendName . An empty backendName is understood as a query about the currently active backend.

该函数在 Qt 6.1 引入。

另请参阅 QSsl::SupportedFeature and supportedFeatures ().

[static, since 6.1] bool QSslSocket:: isProtocolSupported ( QSsl::SslProtocol protocol , const QString & backendName = {})

返回 true 若 protocol is supported by a backend named backendName . An empty backendName is understood as a query about the currently active backend.

该函数在 Qt 6.1 引入。

另请参阅 supportedProtocols ().

QSslCertificate QSslSocket:: localCertificate () const

返回套接字的本地 certificate ,或空证书若没有赋值本地证书。

另请参阅 setLocalCertificate () 和 privateKey ().

QList < QSslCertificate > QSslSocket:: localCertificateChain () const

返回套接字的本地 certificate 链,或空列表若没有赋值本地证书。

另请参阅 setLocalCertificateChain ().

QSslSocket::SslMode QSslSocket:: mode () const

返回套接字的当前模式; UnencryptedMode ,其中 QSslSocket behaves identially to QTcpSocket , or one of SslClientMode or SslServerMode , where the client is either negotiating or in encrypted mode.

当模式改变时, QSslSocket 发射 modeChanged ()

另请参阅 SslMode .

[signal] void QSslSocket:: modeChanged ( QSslSocket::SslMode mode )

此信号被发射当 QSslSocket 改变从 QSslSocket::UnencryptedMode QSslSocket::SslClientMode or QSslSocket::SslServerMode . mode 是新模式。

另请参阅 QSslSocket::mode ().

[signal] void QSslSocket:: newSessionTicketReceived ()

If TLS 1.3 protocol was negotiated during a handshake, QSslSocket emits this signal after receiving NewSessionTicket message. Session and session ticket's lifetime hint are updated in the socket's configuration. The session can be used for session resumption (and a shortened handshake) in future TLS connections.

注意: This functionality enabled only with OpenSSL backend and requires OpenSSL v 1.1.1 or above.

另请参阅 QSslSocket::sslConfiguration (), QSslConfiguration::sessionTicket (),和 QSslConfiguration::sessionTicketLifeTimeHint ().

QList < QOcspResponse > QSslSocket:: ocspResponses () const

This function returns Online Certificate Status Protocol responses that a server may send during a TLS handshake using OCSP stapling. The list is empty if no definitive response or no response at all was received.

另请参阅 QSslConfiguration::setOcspStaplingEnabled ().

QSslCertificate QSslSocket:: peerCertificate () const

Returns the peer's digital certificate (i.e., the immediate certificate of the host you are connected to), or a null certificate, if the peer has not assigned a certificate.

The peer certificate is checked automatically during the handshake phase, so this function is normally used to fetch the certificate for display or for connection diagnostic purposes. It contains information about the peer, including its host name, the certificate issuer, and the peer's public key.

Because the peer certificate is set during the handshake phase, it is safe to access the peer certificate from a slot connected to the sslErrors () 信号或 encrypted () 信号。

If a null certificate is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to doesn't have a certificate, or it can mean there is no connection.

If you want to check the peer's complete chain of certificates, use peerCertificateChain () to get them all at once.

另请参阅 peerCertificateChain ().

QList < QSslCertificate > QSslSocket:: peerCertificateChain () const

Returns the peer's chain of digital certificates, or an empty list of certificates.

Peer certificates are checked automatically during the handshake phase. This function is normally used to fetch certificates for display, or for performing connection diagnostics. Certificates contain information about the peer and the certificate issuers, including host name, issuer names, and issuer public keys.

The peer certificates are set in QSslSocket during the handshake phase, so it is safe to call this function from a slot connected to the sslErrors () 信号或 encrypted () 信号。

If an empty list is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to doesn't have a certificate, or it can mean there is no connection.

If you want to get only the peer's immediate certificate, use peerCertificate ().

另请参阅 peerCertificate ().

int QSslSocket:: peerVerifyDepth () const

Returns the maximum number of certificates in the peer's certificate chain to be checked during the SSL handshake phase, or 0 (the default) if no maximum depth has been set, indicating that the whole certificate chain should be checked.

The certificates are checked in issuing order, starting with the peer's own certificate, then its issuer's certificate, and so on.

另请参阅 setPeerVerifyDepth () 和 peerVerifyMode ().

[signal] void QSslSocket:: peerVerifyError (const QSslError & error )

QSslSocket 可以在 SSL 握手期间多次发射此信号,在建立加密之前,以指示当建立对等方的标识时有发生错误。 error 通常指示 QSslSocket 无法安全标识对等方。

This signal provides you with an early indication when something's wrong. By connecting to this signal, you can manually choose to tear down the connection from inside the connected slot before the handshake has completed. If no action is taken, QSslSocket 将继续进行以发射 QSslSocket::sslErrors ().

另请参阅 sslErrors ().

QSslSocket::PeerVerifyMode QSslSocket:: peerVerifyMode () const

Returns the socket's verify mode. This mode decides whether QSslSocket should request a certificate from the peer (i.e., the client requests a certificate from the server, or a server requesting a certificate from the client), and whether it should require that this certificate is valid.

默认模式为 AutoVerifyPeer ,其告诉 QSslSocket 要使用 VerifyPeer 对于客户端和 QueryPeer 对于服务器。

另请参阅 setPeerVerifyMode (), peerVerifyDepth (),和 mode ().

QString QSslSocket:: peerVerifyName () const

Returns the different hostname for the certificate validation, as set by setPeerVerifyName 或通过 connectToHostEncrypted .

另请参阅 setPeerVerifyName () 和 connectToHostEncrypted ().

[signal] void QSslSocket:: preSharedKeyAuthenticationRequired ( QSslPreSharedKeyAuthenticator * authenticator )

QSslSocket 发射此信号当它协商 PSK (预共享密钥) 密码套件时,因此接着需要 PSK 身份验证。

当使用 PSK 时,客户端必须向服务器发送有效标识和有效 PSK (预共享密钥) 以便 SSL 握手得以继续。应用程序可以在此信号连接的槽中提供此信息,通过填入传递的 authenticator 对象根据需要。

注意: 忽略此信号或未能提供要求证书,将导致握手失败,因此连接将被中止。

注意: The authenticator 对象由套接字所拥有且不能被删除通过应用程序。

另请参阅 QSslPreSharedKeyAuthenticator .

QSslKey QSslSocket:: privateKey () const

返回此套接字的私钥。

另请参阅 setPrivateKey () 和 localCertificate ().

QSsl::SslProtocol QSslSocket:: protocol () const

返回套接字的 SSL 协议。默认情况下, QSsl::SecureProtocols 被使用。

另请参阅 setProtocol ().

[override virtual protected] qint64 QSslSocket:: readData ( char * data , qint64 maxlen )

重实现: QAbstractSocket::readData (char *data, qint64 maxSize).

[override virtual] void QSslSocket:: resume ()

重实现: QAbstractSocket::resume ().

Continues data transfer on the socket after it has been paused. If "setPauseMode( QAbstractSocket::PauseOnSslErrors );" has been called on this socket and a sslErrors () signal is received, calling this method is necessary for the socket to continue.

另请参阅 QAbstractSocket::pauseMode () 和 QAbstractSocket::setPauseMode ().

QSslCipher QSslSocket:: sessionCipher () const

返回套接字的加密 cipher , or a null cipher if the connection isn't encrypted. The socket's cipher for the session is set during the handshake phase. The cipher is used to encrypt and decrypt data transmitted through the socket.

QSslSocket also provides functions for setting the ordered list of ciphers from which the handshake phase will eventually select the session cipher. This ordered list must be in place before the handshake phase begins.

另请参阅 QSslConfiguration::ciphers (), QSslConfiguration::setCiphers (), QSslConfiguration::setCiphers (), QSslConfiguration::ciphers (),和 QSslConfiguration::supportedCiphers ().

QSsl::SslProtocol QSslSocket:: sessionProtocol () const

Returns the socket's SSL/TLS protocol or UnknownProtocol if the connection isn't encrypted. The socket's protocol for the session is set during the handshake phase.

另请参阅 protocol () 和 setProtocol ().

[static, since 6.1] bool QSslSocket:: setActiveBackend (const QString & backendName )

Returns true if a backend with name backendName was set as active backend. backendName must be one of names returned by availableBackends ().

注意: An application cannot mix different backends simultaneously. This implies that a non-default backend must be selected prior to any use of QSslSocket or related classes, e.g. QSslCertificate or QSslKey .

该函数在 Qt 6.1 引入。

另请参阅 activeBackend () 和 availableBackends ().

void QSslSocket:: setLocalCertificate (const QSslCertificate & certificate )

Sets the socket's local certificate to certificate . The local certificate is necessary if you need to confirm your identity to the peer. It is used together with the private key; if you set the local certificate, you must also set the private key.

The local certificate and private key are always necessary for server sockets, but are also rarely used by client sockets if the server requires the client to authenticate.

注意: Secure Transport SSL backend on macOS may update the default keychain (the default is probably your login keychain) by importing your local certificates and keys. This can also result in system dialogs showing up and asking for permission when your application is using these private keys. If such behavior is undesired, set the QT_SSL_USE_TEMPORARY_KEYCHAIN environment variable to a non-zero value; this will prompt QSslSocket to use its own temporary keychain.

另请参阅 localCertificate () 和 setPrivateKey ().

void QSslSocket:: setLocalCertificate (const QString & path , QSsl::EncodingFormat format = QSsl::Pem)

这是重载函数。

Sets the socket's local certificate to the first one found in file path , which is parsed according to the specified format .

void QSslSocket:: setLocalCertificateChain (const QList < QSslCertificate > & localChain )

Sets the certificate chain to be presented to the peer during the SSL handshake to be localChain .

另请参阅 localCertificateChain () 和 QSslConfiguration::setLocalCertificateChain ().

void QSslSocket:: setPeerVerifyDepth ( int depth )

Sets the maximum number of certificates in the peer's certificate chain to be checked during the SSL handshake phase, to depth . Setting a depth of 0 means that no maximum depth is set, indicating that the whole certificate chain should be checked.

The certificates are checked in issuing order, starting with the peer's own certificate, then its issuer's certificate, and so on.

另请参阅 peerVerifyDepth () 和 setPeerVerifyMode ().

void QSslSocket:: setPeerVerifyMode ( QSslSocket::PeerVerifyMode mode )

Sets the socket's verify mode to mode . This mode decides whether QSslSocket should request a certificate from the peer (i.e., the client requests a certificate from the server, or a server requesting a certificate from the client), and whether it should require that this certificate is valid.

默认模式为 AutoVerifyPeer ,其告诉 QSslSocket 要使用 VerifyPeer 对于客户端和 QueryPeer 对于服务器。

Setting this mode after encryption has started has no effect on the current connection.

另请参阅 peerVerifyMode (), setPeerVerifyDepth (),和 mode ().

void QSslSocket:: setPeerVerifyName (const QString & hostName )

Sets a different host name, given by hostName , for the certificate validation instead of the one used for the TCP connection.

另请参阅 peerVerifyName () 和 connectToHostEncrypted ().

void QSslSocket:: setPrivateKey (const QSslKey & key )

设置套接字的私有 key to key . The private key and the local certificate are used by clients and servers that must prove their identity to SSL peers.

Both the key and the local certificate are required if you are creating an SSL server socket. If you are creating an SSL client socket, the key and local certificate are required if your client must identify itself to an SSL server.

另请参阅 privateKey () 和 setLocalCertificate ().

void QSslSocket:: setPrivateKey (const QString & fileName , QSsl::KeyAlgorithm algorithm = QSsl::Rsa, QSsl::EncodingFormat format = QSsl::Pem, const QByteArray & passPhrase = QByteArray())

这是重载函数。

读取字符串在文件 fileName 并解码它使用指定 algorithm 和编码 format 以构造 SSL key . If the encoded key is encrypted, passPhrase is used to decrypt it.

The socket's private key is set to the constructed key. The private key and the local certificate are used by clients and servers that must prove their identity to SSL peers.

Both the key and the local certificate are required if you are creating an SSL server socket. If you are creating an SSL client socket, the key and local certificate are required if your client must identify itself to an SSL server.

另请参阅 privateKey () 和 setLocalCertificate ().

void QSslSocket:: setProtocol ( QSsl::SslProtocol protocol )

将套接字的 SSL (安全套接字层) 协议设为 protocol 。这将影响下次初启握手;在已加密套接字调用此函数,不会影响套接字协议。

另请参阅 protocol ().

[override virtual] void QSslSocket:: setReadBufferSize ( qint64 size )

重实现: QAbstractSocket::setReadBufferSize (qint64 size).

设置尺寸为 QSslSocket 的内部读取缓冲到 size 字节。

[override virtual] bool QSslSocket:: setSocketDescriptor ( qintptr socketDescriptor , QAbstractSocket::SocketState state = ConnectedState, QIODeviceBase::OpenMode openMode = ReadWrite)

重实现: QAbstractSocket::setSocketDescriptor (qintptr socketDescriptor, QAbstractSocket::SocketState socketState, QIODeviceBase::OpenMode openMode).

初始化 QSslSocket 采用本机套接字描述符 socketDescriptor 。返回 true if socketDescriptor 被接受作为有效套接字描述符;否则返回 false 。以指定模式打开套接字通过 openMode ,并进入指定套接字状态通过 state .

注意: 采用相同本机套接字描述符初始化 2 套接字是不可能的。

另请参阅 socketDescriptor ().

[override virtual] void QSslSocket:: setSocketOption ( QAbstractSocket::SocketOption option , const QVariant & value )

重实现: QAbstractSocket::setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value).

设置给定 option 到描述值 value .

另请参阅 socketOption ().

void QSslSocket:: setSslConfiguration (const QSslConfiguration & configuration )

把套接字的 SSL 配置内容设为 configuration . This function sets the local certificate, the ciphers, the private key and the CA certificates to those stored in configuration .

设置 SSL (安全套接字层) 状态相关字段是不可能的。

另请参阅 sslConfiguration (), setLocalCertificate (), setPrivateKey (), QSslConfiguration::setCaCertificates (),和 QSslConfiguration::setCiphers ().

[override virtual protected] qint64 QSslSocket:: skipData ( qint64 maxSize )

重实现: QAbstractSocket::skipData (qint64 maxSize).

[override virtual] QVariant QSslSocket:: socketOption ( QAbstractSocket::SocketOption option )

重实现: QAbstractSocket::socketOption (QAbstractSocket::SocketOption option).

返回值为 option 选项。

另请参阅 setSocketOption ().

QSslConfiguration QSslSocket:: sslConfiguration () const

Returns the socket's SSL configuration state. The default SSL configuration of a socket is to use the default ciphers, default CA certificates, no local private key or certificate.

SSL 配置还包含没有通知可以随时改变的字段。

另请参阅 setSslConfiguration (), localCertificate (), peerCertificate (), peerCertificateChain (), sessionCipher (), privateKey (), QSslConfiguration::ciphers (),和 QSslConfiguration::caCertificates ().

[signal] void QSslSocket:: sslErrors (const QList < QSslError > & errors )

QSslSocket 发射此信号在 SSL 握手之后以指示当建立对等方标识时有发生一个或多个错误。错误通常指示 QSslSocket 无法安全地识别对等方。除非采取任何行动,连接将被丢弃在此信号被发射之后。

If you want to continue connecting despite the errors that have occurred, you must call QSslSocket::ignoreSslErrors () from inside a slot connected to this signal. If you need to access the error list at a later point, you can call sslHandshakeErrors ().

errors 包含一个或多个错误阻止 QSslSocket 验证对等方身份。

注意: 不可以使用 Qt::QueuedConnection 当连接到此信号时,或调用 QSslSocket::ignoreSslErrors () 没有起作用。

另请参阅 peerVerifyError ().

QList < QSslError > QSslSocket:: sslHandshakeErrors () const

Returns a list of the last SSL errors that occurred. This is the same list as QSslSocket passes via the sslErrors () signal. If the connection has been encrypted with no errors, this function will return an empty list.

另请参阅 connectToHostEncrypted ().

[static] long QSslSocket:: sslLibraryBuildVersionNumber ()

Returns the version number of the SSL library in use at compile time. If no SSL support is available then this will return -1.

另请参阅 sslLibraryVersionNumber ().

[static] QString QSslSocket:: sslLibraryBuildVersionString ()

Returns the version string of the SSL library in use at compile time. If no SSL support is available then this will return an empty value.

另请参阅 sslLibraryVersionString ().

[static] long QSslSocket:: sslLibraryVersionNumber ()

Returns the version number of the SSL library in use. Note that this is the version of the library in use at run-time not compile time. If no SSL support is available then this will return -1.

[static] QString QSslSocket:: sslLibraryVersionString ()

Returns the version string of the SSL library in use. Note that this is the version of the library in use at run-time not compile time. If no SSL support is available then this will return an empty value.

[slot] void QSslSocket:: startClientEncryption ()

启动延迟 SSL (安全套接字层) 握手为客户端连接。可以调用此函数当套接字在 ConnectedState 但仍处于 UnencryptedMode 。若尚未连接 (或已加密),此函数不起作用。

有实现 STARTTLS 功能的客户端经常使用延迟 SSL 握手。大多数其它客户端可以避免直接调用此函数通过使用 connectToHostEncrypted () 代替,自动履行握手。

另请参阅 connectToHostEncrypted () 和 startServerEncryption ().

[slot] void QSslSocket:: startServerEncryption ()

Starts a delayed SSL handshake for a server connection. This function can be called when the socket is in the ConnectedState 但仍处于 UnencryptedMode . If it is not connected or it is already encrypted, the function has no effect.

For server sockets, calling this function is the only way to initiate the SSL handshake. Most servers will call this function immediately upon receiving a connection, or as a result of having received a protocol-specific command to enter SSL mode (e.g, the server may respond to receiving the string "STARTTLS\r\n" by calling this function).

实现 SSL 服务器的最常见方式是创建子类化的 QTcpServer 并重实现 QTcpServer::incomingConnection (). The returned socket descriptor is then passed to QSslSocket::setSocketDescriptor ().

另请参阅 connectToHostEncrypted () 和 startClientEncryption ().

[static, since 6.1] QList < QSsl::SupportedFeature > QSslSocket:: supportedFeatures (const QString & backendName = {})

This function returns features supported by a backend named backendName . An empty backendName is understood as a query about the currently active backend.

该函数在 Qt 6.1 引入。

另请参阅 QSsl::SupportedFeature and activeBackend ().

[static, since 6.1] QList < QSsl::SslProtocol > QSslSocket:: supportedProtocols (const QString & backendName = {})

If a backend with name backendName is available, this function returns the list of TLS protocol versions supported by this backend. An empty backendName is understood as a query about the currently active backend. Otherwise, this function returns an empty list.

该函数在 Qt 6.1 引入。

另请参阅 availableBackends (), activeBackend (),和 isProtocolSupported ().

[static] bool QSslSocket:: supportsSsl ()

返回 true 若此平台支持 SSL;否则,返回 false。若平台不支持 SSL,套接字将在连接阶段失败。

[override virtual] bool QSslSocket:: waitForBytesWritten ( int msecs = 30000)

重实现: QAbstractSocket::waitForBytesWritten (int msecs).

[override virtual] bool QSslSocket:: waitForConnected ( int msecs = 30000)

重实现: QAbstractSocket::waitForConnected (int msecs).

等待直到套接字被连接或 msecs 毫秒,以先发生的为准。若连接已建立,此函数返回 true ;否则它返回 false .

另请参阅 QAbstractSocket::waitForConnected ().

[override virtual] bool QSslSocket:: waitForDisconnected ( int msecs = 30000)

重实现: QAbstractSocket::waitForDisconnected (int msecs).

等待直到套接字已断开连接或 msecs 毫秒,以先到的为准。若连接已断开,此函数返回 true ;否则它返回 false .

另请参阅 QAbstractSocket::waitForDisconnected ().

bool QSslSocket:: waitForEncrypted ( int msecs = 30000)

等待直到套接字完成 SSL 握手且有发射 encrypted (),或 msecs 毫秒,以先到的为准。若 encrypted () 已发射,此函数返回 true;否则 (如:套接字断开连接,或 SSL 握手失败) 返回 false。

以下范例为加密套接字最多等待 1 秒:

socket->connectToHostEncrypted("imap", 993);
if (socket->waitForEncrypted(1000))
    qDebug("Encrypted!");
					

若 msecs 为 -1,此函数不会超时。

另请参阅 startClientEncryption (), startServerEncryption (), encrypted (),和 isEncrypted ().

[override virtual] bool QSslSocket:: waitForReadyRead ( int msecs = 30000)

重实现: QAbstractSocket::waitForReadyRead (int msecs).

[override virtual protected] qint64 QSslSocket:: writeData (const char * data , qint64 len )

重实现: QAbstractSocket::writeData (const char *data, qint64 size).

相关非成员

[since 6.0] enum class AlertLevel

描述警报消息的级别

This enum describes the level of an alert message that was sent or received.

常量 描述
QSslSocket::AlertLevel::Warning 0 Non-fatal alert message
QSslSocket::AlertLevel::Fatal 1 Fatal alert message, the underlying backend will handle such an alert properly and close the connection.
QSslSocket::AlertLevel::Unknown 2 An alert of unknown level of severity.

This enum was introduced in Qt 6.0.

[since 6.0] enum class AlertType

枚举警报消息可以拥有的可能代码

RFC 8446, section 6 for the possible values and their meaning.

常量 描述
QSslSocket::AlertType::CloseNotify 0 ,
QSslSocket::AlertType::UnexpectedMessage 10
QSslSocket::AlertType::BadRecordMac 20
QSslSocket::AlertType::RecordOverflow 22
QSslSocket::AlertType::DecompressionFailure 30
QSslSocket::AlertType::HandshakeFailure 40
QSslSocket::AlertType::NoCertificate 41
QSslSocket::AlertType::BadCertificate 42
QSslSocket::AlertType::UnsupportedCertificate 43
QSslSocket::AlertType::CertificateRevoked 44
QSslSocket::AlertType::CertificateExpired 45
QSslSocket::AlertType::CertificateUnknown 46
QSslSocket::AlertType::IllegalParameter 47
QSslSocket::AlertType::UnknownCa 48
QSslSocket::AlertType::AccessDenied 49
QSslSocket::AlertType::DecodeError 50
QSslSocket::AlertType::DecryptError 51
QSslSocket::AlertType::ExportRestriction 60
QSslSocket::AlertType::ProtocolVersion 70
QSslSocket::AlertType::InsufficientSecurity 71
QSslSocket::AlertType::InternalError 80
QSslSocket::AlertType::InappropriateFallback 86
QSslSocket::AlertType::UserCancelled 90
QSslSocket::AlertType::NoRenegotiation 100
QSslSocket::AlertType::MissingExtension 109
QSslSocket::AlertType::UnsupportedExtension 110
QSslSocket::AlertType::CertificateUnobtainable 111
QSslSocket::AlertType::UnrecognizedName 112
QSslSocket::AlertType::BadCertificateStatusResponse 113
QSslSocket::AlertType::BadCertificateHashValue 114
QSslSocket::AlertType::UnknownPskIdentity 115
QSslSocket::AlertType::CertificateRequired 116
QSslSocket::AlertType::NoApplicationProtocol 120
QSslSocket::AlertType::UnknownAlertMessage 255

This enum was introduced in Qt 6.0.

[since 6.1] enum class ImplementedClass

枚举 TLS (传输层安全) 后端实现的类

QtNetwork , some classes have backend-specific implementation and thus can be left unimplemented. Enumerators in this enum indicate, which class has a working implementation in the backend.

常量 描述
QSslSocket::ImplementedClass::Key 0 QSslKey .
QSslSocket::ImplementedClass::Certificate 1 QSslCertificate .
QSslSocket::ImplementedClass::Socket 2 QSslSocket .
QSslSocket::ImplementedClass::DiffieHellman 3 QSslDiffieHellmanParameters .
QSslSocket::ImplementedClass::EllipticCurve 4 QSslEllipticCurve .
QSslSocket::ImplementedClass::Dtls 5 QDtls .
QSslSocket::ImplementedClass::DtlsCookie 6 QDtlsClientVerifier .

This enum was introduced in Qt 6.1.

[since 6.1] enum class SupportedFeature

枚举 TLS (传输层安全) 后端支持的可能特征

QtNetwork TLS-related classes have public API, that may be left unimplemented by some backend, for example, our SecureTransport backend does not support server-side ALPN. Enumerators from SupportedFeature enum indicate that a particular feature is supported.

常量 描述
QSslSocket::SupportedFeature::CertificateVerification 0 指示 QSslCertificate::verify () is implemented by the backend.
QSslSocket::SupportedFeature::ClientSideAlpn 1 Client-side ALPN (Application Layer Protocol Negotiation).
QSslSocket::SupportedFeature::ServerSideAlpn 2 Server-side ALPN.
QSslSocket::SupportedFeature::Ocsp 3 OCSP stapling (Online Certificate Status Protocol).
QSslSocket::SupportedFeature::Psk 4 Pre-shared keys.
QSslSocket::SupportedFeature::SessionTicket 5 Session tickets.
QSslSocket::SupportedFeature::Alerts 6 Information about alert messages sent and received.

This enum was introduced in Qt 6.1.