PySide6.QtNetwork.QSslSocket¶
- class QSslSocket¶
- The - QSslSocketclass provides an SSL encrypted socket for both clients and servers. More…- Synopsis¶- Methods¶- def - __init__()
- def - isEncrypted()
- def - mode()
- def - ocspResponses()
- def - peerVerifyMode()
- def - peerVerifyName()
- def - privateKey()
- def - protocol()
- def - sessionCipher()
- def - setPrivateKey()
- def - setProtocol()
 - Slots¶- Signals¶- def - alertReceived()
- def - alertSent()
- def - encrypted()
- def - modeChanged()
- def - sslErrors()
 - Static functions¶- def - activeBackend()
- def - supportsSsl()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - QSslSocketestablishes 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,- QSslSocketuses only TLS protocols which are considered to be secure (- SecureProtocols), but you can change the TLS protocol by calling- setProtocol()as long as you do it before the handshake has started.- 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.- The most common way to use - QSslSocketis to construct an object and start a secure connection by calling- connectToHostEncrypted(). This method starts an immediate SSL handshake once the connection has been established.- socket = QSslSocket(self) socket.encrypted.connect(self.ready) socket.connectToHostEncrypted("imap.example.com", 993) - As with a plain - QTcpSocket,- QSslSocketenters the HostLookupState, ConnectingState, and finally the ConnectedState, if the connection is successful. The handshake then starts automatically, and if it succeeds, the- encrypted()signal is emitted to indicate the socket has entered the encrypted state and is ready for use.- Note that data can be written to the socket immediately after the return from - connectToHostEncrypted()(i.e., before the- encrypted()signal is emitted). The data is queued in- QSslSocketuntil after the- encrypted()signal is emitted.- 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- incomingConnection()with something like the example below, which first constructs an instance of- QSslSocketand 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().- def incomingConnection(self, socketDescriptor): serverSocket = QSslSocket() if serverSocket.setSocketDescriptor(socketDescriptor): addPendingConnection(serverSocket) serverSocket.encrypted.connect(self.ready) serverSocket.startServerEncryption() else: del serverSocket - If an error occurs, - QSslSocketemits 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- QSslSocketand before the connection is attempted. This will allow- QSslSocketto 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.- Once encrypted, you use - QSslSocketas a regular- QTcpSocket. When readyRead() is emitted, you can call read(),- canReadLine()and readLine(), or getChar() to read decrypted data from- QSslSocket‘s internal buffer, and you can call write() or putChar() to write data back to the peer.- QSslSocketwill automatically encrypt the written data for you, and emit- encryptedBytesWritten()once the data has been written to the peer.- As a convenience, - QSslSocketsupports- QTcpSocket‘s blocking functions- waitForConnected(),- waitForReadyRead(),- waitForBytesWritten(), and- waitForDisconnected(). It also provides- waitForEncrypted(), which will block the calling thread until an encrypted connection has been established.- socket = QSslSocket() socket.connectToHostEncrypted("http.example.com", 443) if not socket.waitForEncrypted(): print(socket.errorString()) return False socket.write("GET / HTTP/1.0\r\n\r\n") while socket.waitForReadyRead(): print(socket.readAll().data()) - QSslSocketprovides 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.- The following features can also be customized: - The socket’s cryptographic cipher suite can be customized before the handshake phase with - setCiphers().
- The socket’s local certificate and private key can be customized before the handshake phase with - setLocalCertificate()and- setPrivateKey().
- The CA certificate database can be extended and customized with - addCaCertificate(),- addCaCertificates().
 - 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); - Note - 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 - defaultConfiguration().setCaCertificates() before the first SSL handshake is made in your application (for example, via passing QSslSocket::systemCaCertificates() to it), or call- defaultConfiguration()::setCaCertificates() on your- QSslSocketinstance prior to the SSL handshake.- For more information about ciphers and certificates, refer to - QSslCipherand- QSslCertificate.- This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit ( http://www.openssl.org/ ). - Note - 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.- See also - class SslMode¶
- Describes the connection modes available for - QSslSocket.- Constant - Description - QSslSocket.UnencryptedMode - The socket is unencrypted. Its behavior is identical to - QTcpSocket.- QSslSocket.SslClientMode - The socket is a client-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see - isEncrypted()).- QSslSocket.SslServerMode - The socket is a server-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see - isEncrypted()).
 - class PeerVerifyMode¶
- Describes the peer verification modes for - QSslSocket. The default mode is AutoVerifyPeer, which selects an appropriate mode depending on the socket’s QSocket::SslMode.- Constant - Description - QSslSocket.VerifyNone - QSslSocketwill 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 - QSslSocketwill 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 - QSslSocketwill request a certificate from the peer during the SSL handshake phase, and requires that this certificate is valid. On failure,- QSslSocketwill emit the- sslErrors()signal. This mode is the default for clients.- QSslSocket.AutoVerifyPeer - QSslSocketwill automatically use QueryPeer for server sockets and VerifyPeer for client sockets.- See also 
 - Constructs a - QSslSocketobject.- parentis passed to QObject’s constructor. The new socket’s- ciphersuite is set to the one returned by the static method defaultCiphers().- static activeBackend()¶
- Return type:
- str 
 
 - Returns the name of the backend that - QSslSocketand related classes use. If the active backend was not set explicitly, this function returns the name of a default backend that- QSslSocketselects implicitly from the list of available backends.- Note - When selecting a default backend implicitly, - QSslSocketprefers the OpenSSL backend if available. If it’s not available, the Schannel backend is implicitly selected on Windows, and Secure Transport on Darwin platforms. Failing these, if a custom TLS backend is found, it is used. If no other backend is found, the “certificate only” backend is selected. For more information about TLS plugins, please see Enabling and Disabling SSL Support when Building Qt from Source .- See also - alertReceived(level, type, description)¶
- Parameters:
- level – - AlertLevel
- type – - AlertType
- description – str 
 
 
 - QSslSocketemits this signal if an alert message was received from a peer.- leveltells if the alert was fatal or it was a warning.- typeis the code explaining why the alert was sent. When a textual description of the alert message is available, it is supplied in- description.- Note - 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(level, type, description)¶
- Parameters:
- level – - AlertLevel
- type – - AlertType
- description – str 
 
 
 - QSslSocketemits this signal if an alert message was sent to a peer.- leveldescribes if it was a warning or a fatal error.- typegives the code of the alert message. When a textual description of the alert message is available, it is supplied in- description.- Note - This signal is mostly informational and can be used for debugging purposes, normally it does not require any actions from the application. - static availableBackends()¶
- Return type:
- .list of QString 
 
 - 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). - See also - connectToHostEncrypted(hostName, port[, mode=QIODeviceBase.OpenModeFlag.ReadWrite[, protocol=QAbstractSocket.NetworkLayerProtocol.AnyIPProtocol]])¶
- Parameters:
- hostName – str 
- port – int 
- mode – Combination of - OpenModeFlag
- protocol – - NetworkLayerProtocol
 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Starts an encrypted connection to the device - hostNameon- port, using- modeas the OpenMode. This is equivalent to calling- connectToHost()to establish the connection, followed by a call to- startClientEncryption(). The- protocolparameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).- QSslSocketfirst enters the HostLookupState. Then, after entering either the event loop or one of the waitFor…() functions, it enters the ConnectingState, emits- connected(), and then initiates the SSL client handshake. At each state change,- QSslSocketemits signal- stateChanged().- After initiating the SSL client handshake, if the identity of the peer can’t be established, signal - 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- QSslSocketreturns to the UnconnectedState.- If the SSL handshake is successful, - QSslSocketemits- encrypted().- socket = QSslSocket() socket.encrypted.connect(receiver.socketEncrypted) socket.connectToHostEncrypted("imap", 993) socket.write("1 CAPABILITY\r\n") - Note - 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()signal has been emitted.- The default for - modeis ReadWrite.- If you want to create a - QSslSocketon the server side of a connection, you should instead call- startServerEncryption()upon receiving the incoming connection through- QTcpServer.- See also - connectToHost()- startClientEncryption()- waitForConnected()- waitForEncrypted()- connectToHostEncrypted(hostName, port, sslPeerName[, mode=QIODeviceBase.OpenModeFlag.ReadWrite[, protocol=QAbstractSocket.NetworkLayerProtocol.AnyIPProtocol]])
- Parameters:
- hostName – str 
- port – int 
- sslPeerName – str 
- mode – Combination of - OpenModeFlag
- protocol – - NetworkLayerProtocol
 
 
 - This is an overloaded function. - 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).- See also - 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.- encrypted()¶
 - This signal is emitted when - QSslSocketenters encrypted mode. After this signal has been emitted,- isEncrypted()will return true, and all further transmissions on the socket will be encrypted.- See also - encryptedBytesAvailable()¶
- Return type:
- int 
 
 - Returns the number of encrypted bytes that are awaiting decryption. Normally, this function will return 0 because - QSslSocketdecrypts its incoming data as soon as it can.- encryptedBytesToWrite()¶
- Return type:
- int 
 
 - Returns the number of encrypted bytes that are waiting to be written to the network. - encryptedBytesWritten(totalBytes)¶
- Parameters:
- totalBytes – int 
 
 - This signal is emitted when - QSslSocketwrites its encrypted data to the network. The- writtenparameter contains the number of bytes that were successfully written.- See also - QSslSocketemits 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- errorand 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.- ignoreSslErrors()¶
 - This slot tells - QSslSocketto ignore errors during- QSslSocket‘s handshake phase and continue connecting. If you want to continue with the connection even if errors occur during the handshake phase, then you must call this slot, either from a slot connected to- sslErrors(), or before the handshake phase. If you don’t call this slot, either in response to errors or before the handshake, the connection will be dropped after the- sslErrors()signal has been emitted.- If there are no errors during the SSL handshake phase (i.e., the identity of the peer is established with no problems), - QSslSocketwill not emit the- sslErrors()signal, and it is unnecessary to call this function.- Warning - Be sure to always let the user inspect the errors reported by the - sslErrors()signal, and only call this method upon confirmation from the user that proceeding is ok. If there are unexpected errors, the connection should be aborted. Calling this method without inspecting the actual errors will most likely pose a security risk for your application. Use it with great care!- See also - ignoreSslErrors(errors)
- Parameters:
- errors – .list of QSslError 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - This method tells - QSslSocketto ignore only the errors given in- errors.- Note - 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: - cert = QSslCertificate.fromPath("server-certificate.pem") error = QSslError(QSslError.SelfSignedCertificate, cert.at(0)) expectedSslErrors = QList() expectedSslErrors.append(error) socket = QSslSocket() socket.ignoreSslErrors(expectedSslErrors) socket.connectToHostEncrypted("server.tld", 443) - Multiple calls to this function will replace the list of errors that were passed in previous calls. You can clear the list of errors you want to ignore by calling this function with an empty list. - See also - static implementedClasses([backendName={}])¶
- Parameters:
- backendName – str 
- Return type:
- .list of QSsl.ImplementedClass 
 
 - This function returns backend-specific classes implemented by the backend named - backendName. An empty- backendNameis understood as a query about the currently active backend.- See also - ImplementedClass- activeBackend()- isClassImplemented()- static isClassImplemented(cl[, backendName={}])¶
- Parameters:
- cl – - ImplementedClass
- backendName – str 
 
- Return type:
- bool 
 
 - Returns true if a class - clis implemented by the backend named- backendName. An empty- backendNameis understood as a query about the currently active backend.- See also - isEncrypted()¶
- Return type:
- bool 
 
 - Returns - trueif the socket is encrypted; otherwise, false is returned.- An encrypted socket encrypts all data that is written by calling write() or putChar() before the data is written to the network, and decrypts all incoming data as the data is received from the network, before you call read(), readLine() or getChar(). - QSslSocketemits- encrypted()when it enters encrypted mode.- You can call - sessionCipher()to find which cryptographic cipher is used to encrypt and decrypt your data.- See also - static isFeatureSupported(feat[, backendName={}])¶
- Parameters:
- feat – - SupportedFeature
- backendName – str 
 
- Return type:
- bool 
 
 - Returns true if a feature - ftis supported by a backend named- backendName. An empty- backendNameis understood as a query about the currently active backend.- See also - SupportedFeature- supportedFeatures()- static isProtocolSupported(protocol[, backendName={}])¶
- Parameters:
- protocol – - SslProtocol
- backendName – str 
 
- Return type:
- bool 
 
 - Returns true if - protocolis supported by a backend named- backendName. An empty- backendNameis understood as a query about the currently active backend.- See also - localCertificate()¶
- Return type:
 
 - Returns the socket’s local - certificate, or an empty certificate if no local certificate has been assigned.- See also - localCertificateChain()¶
- Return type:
- .list of QSslCertificate 
 
 - Returns the socket’s local - certificatechain, or an empty list if no local certificates have been assigned.- See also - Returns the current mode for the socket; either - UnencryptedMode, where- QSslSocketbehaves identially to- QTcpSocket, or one of- SslClientModeor- SslServerMode, where the client is either negotiating or in encrypted mode.- When the mode changes, - QSslSocketemits- modeChanged()- See also - This signal is emitted when - QSslSocketchanges from- UnencryptedModeto either- SslClientModeor- SslServerMode.- modeis the new mode.- See also - newSessionTicketReceived()¶
 - If TLS 1.3 protocol was negotiated during a handshake, - QSslSocketemits 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.- Note - This functionality enabled only with OpenSSL backend and requires OpenSSL v 1.1.1 or above. - ocspResponses()¶
- Return type:
- .list of QOcspResponse 
 
 - 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. - See also - peerCertificate()¶
- Return type:
 
 - 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()signal or the- encrypted()signal.- 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.- See also - peerCertificateChain()¶
- Return type:
- .list of QSslCertificate 
 
 - 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 - QSslSocketduring the handshake phase, so it is safe to call this function from a slot connected to the- sslErrors()signal or the- encrypted()signal.- 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().- See also - peerVerifyDepth()¶
- Return type:
- int 
 
 - 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. - See also - QSslSocketcan emit this signal several times during the SSL handshake, before encryption has been established, to indicate that an error has occurred while establishing the identity of the peer. The- erroris usually an indication that- QSslSocketis unable to securely identify the peer.- 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, - QSslSocketwill proceed to emitting- sslErrors().- See also - peerVerifyMode()¶
- Return type:
 
 - Returns the socket’s verify mode. This mode decides whether - QSslSocketshould 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.- The default mode is - AutoVerifyPeer, which tells- QSslSocketto use- VerifyPeerfor clients and- QueryPeerfor servers.- See also - peerVerifyName()¶
- Return type:
- str 
 
 - Returns the different hostname for the certificate validation, as set by - setPeerVerifyNameor by- connectToHostEncrypted.- Parameters:
- authenticator – - QSslPreSharedKeyAuthenticator
 
 - QSslSocketemits this signal when it negotiates a PSK ciphersuite, and therefore a PSK authentication is then required.- When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the SSL handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed - authenticatorobject according to their needs.- Note - Ignoring this signal, or failing to provide the required credentials, will cause the handshake to fail, and therefore the connection to be aborted. - Note - The - authenticatorobject is owned by the socket and must not be deleted by the application.- See also - Returns this socket’s private key. - See also - protocol()¶
- Return type:
 
 - Returns the socket’s SSL protocol. By default, - SecureProtocolsis used.- See also - sessionCipher()¶
- Return type:
 
 - Returns the socket’s cryptographic - 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.- QSslSocketalso 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.- sessionProtocol()¶
- Return type:
 
 - 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. - See also - static setActiveBackend(backendName)¶
- Parameters:
- backendName – str 
- Return type:
- bool 
 
 - Returns true if a backend with name - backendNamewas set as active backend.- backendNamemust be one of names returned by- availableBackends().- Note - An application cannot mix different backends simultaneously. This implies that a non-default backend must be selected prior to any use of - QSslSocketor related classes, e.g.- QSslCertificateor- QSslKey.- See also - setLocalCertificate(certificate)¶
- Parameters:
- certificate – - QSslCertificate
 
 - 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. - Note - 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 - QSslSocketto use its own temporary keychain.- See also - setLocalCertificate(fileName[, format=QSsl.Pem])
- Parameters:
- fileName – str 
- format – - EncodingFormat
 
 
 - This is an overloaded function. - Sets the socket’s local - certificateto the first one found in file- path, which is parsed according to the specified- format.- setLocalCertificateChain(localChain)¶
- Parameters:
- localChain – .list of QSslCertificate 
 
 - Sets the certificate chain to be presented to the peer during the SSL handshake to be - localChain.- setPeerVerifyDepth(depth)¶
- Parameters:
- depth – int 
 
 - 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. - See also - setPeerVerifyMode(mode)¶
- Parameters:
- mode – - PeerVerifyMode
 
 - Sets the socket’s verify mode to - mode. This mode decides whether- QSslSocketshould 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.- The default mode is - AutoVerifyPeer, which tells- QSslSocketto use- VerifyPeerfor clients and- QueryPeerfor servers.- Setting this mode after encryption has started has no effect on the current connection. - See also - setPeerVerifyName(hostName)¶
- Parameters:
- hostName – str 
 
 - Sets a different host name, given by - hostName, for the certificate validation instead of the one used for the TCP connection.- See also - Sets the socket’s private - keyto- key. The private key and the local- certificateare 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. - See also - setPrivateKey(fileName[, algorithm=QSsl.Rsa[, format=QSsl.Pem[, passPhrase=QByteArray()]]])
- Parameters:
- fileName – str 
- algorithm – - KeyAlgorithm
- format – - EncodingFormat
- passPhrase – - QByteArray
 
 
 - This is an overloaded function. - Reads the string in file - fileNameand decodes it using a specified- algorithmand encoding- formatto construct an- SSL key. If the encoded key is encrypted,- passPhraseis used to decrypt it.- The socket’s private key is set to the constructed key. The private key and the local - certificateare 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. - See also - setProtocol(protocol)¶
- Parameters:
- protocol – - SslProtocol
 
 - Sets the socket’s SSL protocol to - protocol. This will affect the next initiated handshake; calling this function on an already-encrypted socket will not affect the socket’s protocol.- See also - setSslConfiguration(config)¶
- Parameters:
- config – - QSslConfiguration
 
 - Sets the socket’s SSL configuration to be the contents of - configuration. This function sets the local certificate, the ciphers, the private key and the CA certificates to those stored in- configuration.- It is not possible to set the SSL-state related fields. - sslConfiguration()¶
- Return type:
 
 - 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. - The SSL configuration also contains fields that can change with time without notice. - sslErrors(errors)¶
- Parameters:
- errors – .list of QSslError 
 
 - QSslSocketemits this signal after the SSL handshake to indicate that one or more errors have occurred while establishing the identity of the peer. The errors are usually an indication that- QSslSocketis unable to securely identify the peer. Unless any action is taken, the connection will be dropped after this signal has been emitted.- If you want to continue connecting despite the errors that have occurred, you must call - 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().- errorscontains one or more errors that prevent- QSslSocketfrom verifying the identity of the peer.- Note - You cannot use Qt::QueuedConnection when connecting to this signal, or calling - ignoreSslErrors()will have no effect.- See also - Returns a list of the last SSL errors that occurred. This is the same list as - QSslSocketpasses via the- sslErrors()signal. If the connection has been encrypted with no errors, this function will return an empty list.- See also - static sslLibraryBuildVersionNumber()¶
- Return type:
- int 
 
 - Returns the version number of the SSL library in use at compile time. If no SSL support is available then this will return -1. - See also - static sslLibraryBuildVersionString()¶
- Return type:
- str 
 
 - 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. - See also - static sslLibraryVersionNumber()¶
- Return type:
- int 
 
 - 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 sslLibraryVersionString()¶
- Return type:
- str 
 
 - 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. - startClientEncryption()¶
 - Starts a delayed SSL handshake for a client connection. This function can be called when the socket is in the - ConnectedStatebut still in the- UnencryptedMode. If it is not yet connected, or if it is already encrypted, this function has no effect.- Clients that implement STARTTLS functionality often make use of delayed SSL handshakes. Most other clients can avoid calling this function directly by using - connectToHostEncrypted()instead, which automatically performs the handshake.- startServerEncryption()¶
 - Starts a delayed SSL handshake for a server connection. This function can be called when the socket is in the - ConnectedStatebut still in- 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). - The most common way to implement an SSL server is to create a subclass of - QTcpServerand reimplement- incomingConnection(). The returned socket descriptor is then passed to- setSocketDescriptor().- static supportedFeatures([backendName={}])¶
- Parameters:
- backendName – str 
- Return type:
- .list of QSsl.SupportedFeature 
 
 - This function returns features supported by a backend named - backendName. An empty- backendNameis understood as a query about the currently active backend.- See also - SupportedFeature- activeBackend()- static supportedProtocols([backendName={}])¶
- Parameters:
- backendName – str 
- Return type:
- .list of QSsl.SslProtocol 
 
 - If a backend with name - backendNameis available, this function returns the list of TLS protocol versions supported by this backend. An empty- backendNameis understood as a query about the currently active backend. Otherwise, this function returns an empty list.- static supportsSsl()¶
- Return type:
- bool 
 
 - Returns - trueif this platform supports SSL; otherwise, returns false. If the platform doesn’t support SSL, the socket will fail in the connection phase.- waitForEncrypted([msecs=30000])¶
- Parameters:
- msecs – int 
- Return type:
- bool 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Waits until the socket has completed the SSL handshake and has emitted - encrypted(), or- msecsmilliseconds, whichever comes first. If- encrypted()has been emitted, this function returns true; otherwise (e.g., the socket is disconnected, or the SSL handshake fails), false is returned.- The following example waits up to one second for the socket to be encrypted: - socket.connectToHostEncrypted("imap", 993) if socket.waitForEncrypted(1000): qDebug("Encrypted!") - If msecs is -1, this function will not time out.