Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QSslSocket Class

TheQSslSocket class provides an SSL encrypted socket for both clients and servers.More...

Header:#include <QSslSocket>
Since: Qt 4.3
Inherits:QTcpSocket

Note: All functions in this class arereentrant.

Public Types

enumPeerVerifyMode { VerifyNone, QueryPeer, VerifyPeer, AutoVerifyPeer }
enumSslMode { UnencryptedMode, SslClientMode, SslServerMode }

Public Functions

QSslSocket(QObject * parent = 0)
~QSslSocket()
voidabort()
voidaddCaCertificate(const QSslCertificate & certificate)
booladdCaCertificates(const QString & path, QSsl::EncodingFormat format = QSsl::Pem, QRegExp::PatternSyntax syntax = QRegExp::FixedString)
voidaddCaCertificates(const QList<QSslCertificate> & certificates)
QList<QSslCertificate>caCertificates() const
QList<QSslCipher>ciphers() const
voidconnectToHostEncrypted(const QString & hostName, quint16 port, OpenMode mode = ReadWrite)
voidconnectToHostEncrypted(const QString & hostName, quint16 port, const QString & sslPeerName, OpenMode mode = ReadWrite)
qint64encryptedBytesAvailable() const
qint64encryptedBytesToWrite() const
boolflush()
voidignoreSslErrors(const QList<QSslError> & errors)
boolisEncrypted() const
QSslCertificatelocalCertificate() const
SslModemode() const
QSslCertificatepeerCertificate() const
QList<QSslCertificate>peerCertificateChain() const
intpeerVerifyDepth() const
QSslSocket::PeerVerifyModepeerVerifyMode() const
QStringpeerVerifyName() const
QSslKeyprivateKey() const
QSsl::SslProtocolprotocol() const
QSslCiphersessionCipher() const
voidsetCaCertificates(const QList<QSslCertificate> & certificates)
voidsetCiphers(const QList<QSslCipher> & ciphers)
voidsetCiphers(const QString & ciphers)
voidsetLocalCertificate(const QSslCertificate & certificate)
voidsetLocalCertificate(const QString & path, QSsl::EncodingFormat format = QSsl::Pem)
voidsetPeerVerifyDepth(int depth)
voidsetPeerVerifyMode(QSslSocket::PeerVerifyMode mode)
voidsetPeerVerifyName(const QString & hostName)
voidsetPrivateKey(const QSslKey & key)
voidsetPrivateKey(const QString & fileName, QSsl::KeyAlgorithm algorithm = QSsl::Rsa, QSsl::EncodingFormat format = QSsl::Pem, const QByteArray & passPhrase = QByteArray())
voidsetProtocol(QSsl::SslProtocol protocol)
voidsetReadBufferSize(qint64 size)
boolsetSocketDescriptor(int socketDescriptor, SocketState state = ConnectedState, OpenMode openMode = ReadWrite)
voidsetSocketOption(QAbstractSocket::SocketOption option, const QVariant & value)
voidsetSslConfiguration(const QSslConfiguration & configuration)
QVariantsocketOption(QAbstractSocket::SocketOption option)
QSslConfigurationsslConfiguration() const
QList<QSslError>sslErrors() const
boolwaitForConnected(int msecs = 30000)
boolwaitForDisconnected(int msecs = 30000)
boolwaitForEncrypted(int msecs = 30000)

Reimplemented Public Functions

virtual boolatEnd() const
virtual qint64bytesAvailable() const
virtual qint64bytesToWrite() const
virtual boolcanReadLine() const
virtual voidclose()
virtual boolwaitForBytesWritten(int msecs = 30000)
virtual boolwaitForReadyRead(int msecs = 30000)

Public Slots

  • 1 public slot inherited fromQObject

Signals

voidencrypted()
voidencryptedBytesWritten(qint64 written)
voidmodeChanged(QSslSocket::SslMode mode)
voidpeerVerifyError(const QSslError & error)
voidsslErrors(const QList<QSslError> & errors)

Static Public Members

voidaddDefaultCaCertificate(const QSslCertificate & certificate)
booladdDefaultCaCertificates(const QString & path, QSsl::EncodingFormat encoding = QSsl::Pem, QRegExp::PatternSyntax syntax = QRegExp::FixedString)
voidaddDefaultCaCertificates(const QList<QSslCertificate> & certificates)
QList<QSslCertificate>defaultCaCertificates()
QList<QSslCipher>defaultCiphers()
voidsetDefaultCaCertificates(const QList<QSslCertificate> & certificates)
voidsetDefaultCiphers(const QList<QSslCipher> & ciphers)
QList<QSslCipher>supportedCiphers()
boolsupportsSsl()
QList<QSslCertificate>systemCaCertificates()
  • 7 static public members inherited fromQObject

Reimplemented Protected Functions

virtual qint64readData(char * data, qint64 maxlen)
virtual qint64writeData(const char * data, qint64 len)

Additional Inherited Members

Detailed Description

TheQSslSocket class provides an SSL encrypted socket for both clients and servers.

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 SSL protocols, including SSLv3 and TLSv1. By default,QSslSocket uses TLSv1, but you can change the SSL protocol by callingsetProtocol() 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 theConnectedState. There are two simple ways to establish a secure connection usingQSslSocket: 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 useQSslSocket is to construct an object and start a secure connection by callingconnectToHostEncrypted(). This method starts an immediate SSL handshake once the connection has been established.

QSslSocket*socket=newQSslSocket(this);connect(socket, SIGNAL(encrypted()),this, SLOT(ready()));socket->connectToHostEncrypted("imap.example.com",993);

As with a plainQTcpSocket,QSslSocket enters theHostLookupState,ConnectingState, and finally theConnectedState, if the connection is successful. The handshake then starts automatically, and if it succeeds, theencrypted() 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 fromconnectToHostEncrypted() (i.e., before theencrypted() signal is emitted). The data is queued inQSslSocket until after theencrypted() 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 ofQTcpServer. You would overrideQTcpServer::incomingConnection() with something like the example below, which first constructs an instance ofQSslSocket and then callssetSocketDescriptor() to set the new socket's descriptor to the existing one passed in. It then initiates the SSL handshake by callingstartServerEncryption().

void SslServer::incomingConnection(int socketDescriptor){QSslSocket*serverSocket=newQSslSocket;if (serverSocket->setSocketDescriptor(socketDescriptor)) {        connect(serverSocket, SIGNAL(encrypted()),this, SLOT(ready()));        serverSocket->startServerEncryption();    }else {delete serverSocket;    }}

If an error occurs,QSslSocket emits thesslErrors() 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 callignoreSslErrors(), either from within this slot after the error occurs, or any time after construction of theQSslSocket and before the connection is attempted. This will allowQSslSocket 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.

Once encrypted, you useQSslSocket as a regularQTcpSocket. WhenreadyRead() is emitted, you can callread(),canReadLine() andreadLine(), orgetChar() to read decrypted data fromQSslSocket's internal buffer, and you can callwrite() orputChar() to write data back to the peer.QSslSocket will automatically encrypt the written data for you, and emitencryptedBytesWritten() once the data has been written to the peer.

As a convenience,QSslSocket supportsQTcpSocket's blocking functionswaitForConnected(),waitForReadyRead(),waitForBytesWritten(), andwaitForDisconnected(). It also provideswaitForEncrypted(), 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();returnfalse;}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.

The following features can also be customized:

Note:If available, root certificates on Unix (excluding Mac OS X) 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 the static functionsetDefaultCaCertificates() before the first SSL handshake is made in your application, (e.g. via "QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates());"), or callsetCaCertificates() on yourQSslSocket instance prior to the SSL handshake.

For more information about ciphers and certificates, refer toQSslCipher andQSslCertificate.

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 thebytesWritten() signal and theencryptedBytesWritten() signal. For aQTcpSocket,bytesWritten() will get emitted as soon as data has been written to the TCP socket. For aQSslSocket,bytesWritten() will get emitted when the data is being encrypted andencryptedBytesWritten() will get emitted as soon as data has been written to the TCP socket.

Symbian Platform Security Requirements

On Symbian, processes which use this class must have theNetworkServices platform security capability. If the client process lacks this capability, operations will fail.

Platform security capabilities are added via theTARGET.CAPABILITY qmake variable.

See alsoQSslCertificate,QSslCipher, andQSslError.

Member Type Documentation

enum QSslSocket::PeerVerifyMode

Describes the peer verification modes forQSslSocket. The default mode is AutoVerifyPeer, which selects an appropriate mode depending on the socket's QSocket::SslMode.

ConstantValueDescription
QSslSocket::VerifyNone0QSslSocket 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::QueryPeer1QSslSocket 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.
QSslSocket::VerifyPeer2QSslSocket will request a certificate from the peer during the SSL handshake phase, and requires that this certificate is valid. On failure,QSslSocket will emit theQSslSocket::sslErrors() signal. This mode is the default for clients.
QSslSocket::AutoVerifyPeer3QSslSocket will automatically use QueryPeer for server sockets and VerifyPeer for client sockets.

This enum was introduced or modified in Qt 4.4.

See alsoQSslSocket::peerVerifyMode().

enum QSslSocket::SslMode

Describes the connection modes available forQSslSocket.

ConstantValueDescription
QSslSocket::UnencryptedMode0The socket is unencrypted. Its behavior is identical toQTcpSocket.
QSslSocket::SslClientMode1The socket is a client-side SSL socket. It is either alreayd encrypted, or it is in the SSL handshake phase (seeQSslSocket::isEncrypted()).
QSslSocket::SslServerMode2The socket is a server-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (seeQSslSocket::isEncrypted()).

Member Function Documentation

QSslSocket::QSslSocket(QObject * parent = 0)

Constructs aQSslSocket object.parent is passed toQObject's constructor. The new socket'scipher suite is set to the one returned by the static methoddefaultCiphers().

QSslSocket::~QSslSocket()

Destroys theQSslSocket.

void QSslSocket::abort()

Aborts the current connection and resets the socket. UnlikedisconnectFromHost(), this function immediately closes the socket, clearing any pending data in the write buffer.

See alsodisconnectFromHost() andclose().

void QSslSocket::addCaCertificate(constQSslCertificate & certificate)

Adds thecertificate to this socket's CA certificate database. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.

To add multiple certificates, useaddCaCertificates().

See alsocaCertificates() andsetCaCertificates().

bool QSslSocket::addCaCertificates(constQString & path,QSsl::EncodingFormat format = QSsl::Pem,QRegExp::PatternSyntax syntax = QRegExp::FixedString)

Searches all files in thepath for certificates encoded in the specifiedformat and adds them to this socket's CA certificate database.path can be explicit, or it can contain wildcards in the format specified bysyntax. Returns true if one or more certificates are added to the socket's CA certificate database; otherwise returns false.

The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.

For more precise control, useaddCaCertificate().

See alsoaddCaCertificate() andQSslCertificate::fromPath().

void QSslSocket::addCaCertificates(constQList<QSslCertificate> & certificates)

Adds thecertificates to this socket's CA certificate database. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.

For more precise control, useaddCaCertificate().

See alsocaCertificates() andaddDefaultCaCertificate().

[static]void QSslSocket::addDefaultCaCertificate(constQSslCertificate & certificate)

Addscertificate to the default CA certificate database. Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See alsodefaultCaCertificates() andaddCaCertificates().

[static]bool QSslSocket::addDefaultCaCertificates(constQString & path,QSsl::EncodingFormat encoding = QSsl::Pem,QRegExp::PatternSyntax syntax = QRegExp::FixedString)

Searches all files in thepath for certificates with the specifiedencoding and adds them to the default CA certificate database.path can be an explicit file, or it can contain wildcards in the format specified bysyntax. Returns true if any CA certificates are added to the default database.

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See alsodefaultCaCertificates(),addCaCertificates(), andaddDefaultCaCertificate().

[static]void QSslSocket::addDefaultCaCertificates(constQList<QSslCertificate> & certificates)

Addscertificates to the default CA certificate database. Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See alsodefaultCaCertificates() andaddCaCertificates().

[virtual]bool QSslSocket::atEnd() const

Reimplemented fromQIODevice::atEnd().

[virtual]qint64 QSslSocket::bytesAvailable() const

Reimplemented fromQIODevice::bytesAvailable().

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

[virtual]qint64 QSslSocket::bytesToWrite() const

Reimplemented fromQIODevice::bytesToWrite().

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

QList<QSslCertificate> QSslSocket::caCertificates() const

Returns this socket's CA certificate database. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate. It can be moodified prior to the handshake withaddCaCertificate(),addCaCertificates(), andsetCaCertificates().

Note:On Unix, this method may return an empty list if the root certificates are loaded on demand.

See alsoaddCaCertificate(),addCaCertificates(), andsetCaCertificates().

[virtual]bool QSslSocket::canReadLine() const

Reimplemented fromQIODevice::canReadLine().

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

QList<QSslCipher> QSslSocket::ciphers() const

Returns this socket's current cryptographic cipher suite. This list is used during the socket's handshake phase for choosing a session cipher. The returned list of ciphers is ordered by descending preference. (i.e., the first cipher in the list is the most preferred cipher). The session cipher will be the first one in the list that is also supported by the peer.

By default, the handshake phase can choose any of the ciphers supported by this system's SSL libraries, which may vary from system to system. The list of ciphers supported by this system's SSL libraries is returned bysupportedCiphers(). You can restrict the list of ciphers used for choosing the session cipher for this socket by callingsetCiphers() with a subset of the supported ciphers. You can revert to using the entire set by callingsetCiphers() with the list returned bysupportedCiphers().

You can restrict the list of ciphers used for choosing the session cipher forall sockets by callingsetDefaultCiphers() with a subset of the supported ciphers. You can revert to using the entire set by callingsetCiphers() with the list returned bysupportedCiphers().

See alsosetCiphers(),defaultCiphers(),setDefaultCiphers(), andsupportedCiphers().

[virtual]void QSslSocket::close()

Reimplemented fromQIODevice::close().

void QSslSocket::connectToHostEncrypted(constQString & hostName,quint16 port,OpenMode mode = ReadWrite)

Starts an encrypted connection to the devicehostName onport, usingmode as theOpenMode. This is equivalent to callingconnectToHost() to establish the connection, followed by a call tostartClientEncryption().

QSslSocket first enters theHostLookupState. Then, after entering either the event loop or one of the waitFor...() functions, it enters theConnectingState, emitsconnected(), and then initiates the SSL client handshake. At each state change,QSslSocket emits signalstateChanged().

After initiating the SSL client handshake, if the identity of the peer can't be established, signalsslErrors() is emitted. If you want to ignore the errors and continue connecting, you must callignoreSslErrors(), either from inside a slot function connected to thesslErrors() signal, or prior to entering encrypted mode. IfignoreSslErrors() is not called, the connection is dropped, signaldisconnected() is emitted, andQSslSocket returns to theUnconnectedState.

If the SSL handshake is successful,QSslSocket emitsencrypted().

QSslSocket socket;connect(&socket, SIGNAL(encrypted()), receiver, SLOT(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 theencrypted() signal has been emitted. In such cases, the text is queued in the object and written to the socketafter the connection is established and theencrypted() signal has been emitted.

The default formode isReadWrite.

If you want to create aQSslSocket on the server side of a connection, you should instead callstartServerEncryption() upon receiving the incoming connection throughQTcpServer.

See alsoconnectToHost(),startClientEncryption(),waitForConnected(), andwaitForEncrypted().

void QSslSocket::connectToHostEncrypted(constQString & hostName,quint16 port, constQString & sslPeerName,OpenMode mode = ReadWrite)

This is an overloaded function.

In addition to the original behaviour ofconnectToHostEncrypted, 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).

This function was introduced in Qt 4.6.

See alsoconnectToHostEncrypted().

[static]QList<QSslCertificate> QSslSocket::defaultCaCertificates()

Returns the current default CA certificate database. This database is originally set to your system's default CA certificate database. If no system default database is found, an empty database will be returned. You can override the default CA certificate database with your own CA certificate database usingsetDefaultCaCertificates().

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

Note:On Unix, this method may return an empty list if the root certificates are loaded on demand.

See alsosetDefaultCaCertificates() andcaCertificates().

[static]QList<QSslCipher> QSslSocket::defaultCiphers()

Returns the default cryptographic cipher suite for all sockets in this application. This list is used during the socket's handshake phase when negotiating with the peer to choose a session cipher. The list is ordered by preference (i.e., the first cipher in the list is the most preferred cipher).

By default, the handshake phase can choose any of the ciphers supported by this system's SSL libraries, which may vary from system to system. The list of ciphers supported by this system's SSL libraries is returned bysupportedCiphers().

See alsosetDefaultCiphers() andsupportedCiphers().

[signal]void QSslSocket::encrypted()

This signal is emitted whenQSslSocket enters encrypted mode. After this signal has been emitted,QSslSocket::isEncrypted() will return true, and all further transmissions on the socket will be encrypted.

See alsoQSslSocket::connectToHostEncrypted() andQSslSocket::isEncrypted().

qint64 QSslSocket::encryptedBytesAvailable() const

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

This function was introduced in Qt 4.4.

qint64 QSslSocket::encryptedBytesToWrite() const

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

This function was introduced in Qt 4.4.

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

This signal is emitted whenQSslSocket writes its encrypted data to the network. Thewritten parameter contains the number of bytes that were successfully written.

This function was introduced in Qt 4.4.

See alsoQIODevice::bytesWritten().

bool QSslSocket::flush()

This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true; otherwise false is returned.

Call this function if you needQSslSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, becauseQAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, callwaitForBytesWritten() instead.

See alsowrite() andwaitForBytesWritten().

[slot]void QSslSocket::ignoreSslErrors()

This slot tellsQSslSocket to ignore errors duringQSslSocket'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 tosslErrors(), 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 thesslErrors() 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),QSslSocket will not emit thesslErrors() signal, and it is unnecessary to call this function.

Warning: Be sure to always let the user inspect the errors reported by thesslErrors() 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 alsosslErrors().

void QSslSocket::ignoreSslErrors(constQList<QSslError> & errors)

This is an overloaded function.

This method tellsQSslSocket to ignore only the errors given inerrors.

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:

QList<QSslCertificate> cert=QSslCertificate::fromPath(QLatin1String("server-certificate.pem"));QSslErrorerror(QSslError::SelfSignedCertificate, cert.at(0));QList<QSslError> expectedSslErrors;expectedSslErrors.append(error);QSslSocket socket;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.

This function was introduced in Qt 4.6.

See alsosslErrors().

bool QSslSocket::isEncrypted() const

Returns true if the socket is encrypted; otherwise, false is returned.

An encrypted socket encrypts all data that is written by callingwrite() orputChar() before the data is written to the network, and decrypts all incoming data as the data is received from the network, before you callread(),readLine() orgetChar().

QSslSocket emitsencrypted() when it enters encrypted mode.

You can callsessionCipher() to find which cryptographic cipher is used to encrypt and decrypt your data.

See alsomode().

QSslCertificate QSslSocket::localCertificate() const

Returns the socket's localcertificate, or an empty certificate if no local certificate has been assigned.

See alsosetLocalCertificate() andprivateKey().

SslMode QSslSocket::mode() const

Returns the current mode for the socket; eitherUnencryptedMode, whereQSslSocket behaves identially toQTcpSocket, or one ofSslClientMode orSslServerMode, where the client is either negotiating or in encrypted mode.

When the mode changes,QSslSocket emitsmodeChanged()

See alsoSslMode.

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

This signal is emitted whenQSslSocket changes fromQSslSocket::UnencryptedMode to eitherQSslSocket::SslClientMode orQSslSocket::SslServerMode.mode is the new mode.

See alsoQSslSocket::mode().

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 thesslErrors() signal or theencrypted() 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, usepeerCertificateChain() to get them all at once.

See alsopeerCertificateChain().

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 inQSslSocket during the handshake phase, so it is safe to call this function from a slot connected to thesslErrors() signal or theencrypted() 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, usepeerCertificate().

See alsopeerCertificate().

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.

This function was introduced in Qt 4.4.

See alsosetPeerVerifyDepth() andpeerVerifyMode().

[signal]void QSslSocket::peerVerifyError(constQSslError & error)

QSslSocket can 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. Theerror is usually an indication thatQSslSocket is 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,QSslSocket will proceed to emittingQSslSocket::sslErrors().

This function was introduced in Qt 4.4.

See alsosslErrors().

QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode() const

Returns the socket's verify mode. This mode mode decides whetherQSslSocket 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.

The default mode isAutoVerifyPeer, which tellsQSslSocket to useVerifyPeer for clients andQueryPeer for servers.

This function was introduced in Qt 4.4.

See alsosetPeerVerifyMode(),peerVerifyDepth(), andmode().

QString QSslSocket::peerVerifyName() const

Returns the different hostname for the certificate validation, as set bysetPeerVerifyName or byconnectToHostEncrypted.

This function was introduced in Qt 4.8.

See alsosetPeerVerifyName() andconnectToHostEncrypted().

QSslKey QSslSocket::privateKey() const

Returns this socket's private key.

See alsosetPrivateKey() andlocalCertificate().

QSsl::SslProtocol QSslSocket::protocol() const

Returns the socket's SSL protocol. By default,QSsl::SecureProtocols is used.

See alsosetProtocol().

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

Reimplemented fromQIODevice::readData().

QSslCipher QSslSocket::sessionCipher() const

Returns the socket's cryptographiccipher, 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.

See alsociphers(),setCiphers(),setDefaultCiphers(),defaultCiphers(), andsupportedCiphers().

void QSslSocket::setCaCertificates(constQList<QSslCertificate> & certificates)

Sets this socket's CA certificate database to becertificates. The certificate database must be set prior to the SSL handshake. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.

The CA certificate database can be reset to the current default CA certificate database by calling this function with the list of CA certificates returned bydefaultCaCertificates().

See alsocaCertificates() anddefaultCaCertificates().

void QSslSocket::setCiphers(constQList<QSslCipher> & ciphers)

Sets the cryptographic cipher suite for this socket tociphers, which must contain a subset of the ciphers in the list returned bysupportedCiphers().

Restricting the cipher suite must be done before the handshake phase, where the session cipher is chosen.

See alsociphers(),setDefaultCiphers(), andsupportedCiphers().

void QSslSocket::setCiphers(constQString & ciphers)

Sets the cryptographic cipher suite for this socket tociphers, which is a colon-separated list of cipher suite names. The ciphers are listed in order of preference, starting with the most preferred cipher. For example:

QSslSocket socket;socket.setCiphers("DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA");

Each cipher name inciphers must be the name of a cipher in the list returned bysupportedCiphers(). Restricting the cipher suite must be done before the handshake phase, where the session cipher is chosen.

See alsociphers(),setDefaultCiphers(), andsupportedCiphers().

[static]void QSslSocket::setDefaultCaCertificates(constQList<QSslCertificate> & certificates)

Sets the default CA certificate database tocertificates. The default CA certificate database is originally set to your system's default CA certificate database. You can override the default CA certificate database with your own CA certificate database using this function.

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See alsodefaultCaCertificates() andaddDefaultCaCertificate().

[static]void QSslSocket::setDefaultCiphers(constQList<QSslCipher> & ciphers)

Sets the default cryptographic cipher suite for all sockets in this application tociphers, which must contain a subset of the ciphers in the list returned bysupportedCiphers().

Restricting the default cipher suite only affects SSL sockets that perform their handshake phase after the default cipher suite has been changed.

See alsosetCiphers(),defaultCiphers(), andsupportedCiphers().

void QSslSocket::setLocalCertificate(constQSslCertificate & certificate)

Sets the socket's local certificate tocertificate. 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.

See alsolocalCertificate() andsetPrivateKey().

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

This is an overloaded function.

Sets the socket's localcertificate to the first one found in filepath, which is parsed according to the specifiedformat.

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, todepth. 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.

This function was introduced in Qt 4.4.

See alsopeerVerifyDepth() andsetPeerVerifyMode().

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

Sets the socket's verify mode tomode. This mode decides whetherQSslSocket 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.

The default mode isAutoVerifyPeer, which tellsQSslSocket to useVerifyPeer for clients andQueryPeer for servers.

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

This function was introduced in Qt 4.4.

See alsopeerVerifyMode(),setPeerVerifyDepth(), andmode().

void QSslSocket::setPeerVerifyName(constQString & hostName)

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

This function was introduced in Qt 4.8.

See alsopeerVerifyName() andconnectToHostEncrypted().

void QSslSocket::setPrivateKey(constQSslKey & key)

Sets the socket's privatekey tokey. The private key and the localcertificate 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.

See alsoprivateKey() andsetLocalCertificate().

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

This is an overloaded function.

Reads the string in filefileName and decodes it using a specifiedalgorithm and encodingformat to construct anSSL 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 localcertificate 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.

See alsoprivateKey() andsetLocalCertificate().

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

Sets the socket's SSL protocol toprotocol. This will affect the next initiated handshake; calling this function on an already-encrypted socket will not affect the socket's protocol.

See alsoprotocol().

void QSslSocket::setReadBufferSize(qint64 size)

Sets the size ofQSslSocket's internal read buffer to besize bytes.

This function was introduced in Qt 4.4.

bool QSslSocket::setSocketDescriptor(int socketDescriptor,SocketState state = ConnectedState,OpenMode openMode = ReadWrite)

InitializesQSslSocket with the native socket descriptorsocketDescriptor. Returns true ifsocketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified byopenMode, and enters the socket state specified bystate.

Note: It is not possible to initialize two sockets with the same native socket descriptor.

See alsosocketDescriptor().

void QSslSocket::setSocketOption(QAbstractSocket::SocketOption option, constQVariant & value)

Sets the givenoption to the value described byvalue.

This function was introduced in Qt 4.6.

See alsosocketOption().

void QSslSocket::setSslConfiguration(constQSslConfiguration & configuration)

Sets the socket's SSL configuration to be the contents ofconfiguration. This function sets the local certificate, the ciphers, the private key and the CA certificates to those stored inconfiguration.

It is not possible to set the SSL-state related fields.

This function was introduced in Qt 4.4.

See alsosslConfiguration(),setLocalCertificate(),setPrivateKey(),setCaCertificates(), andsetCiphers().

QVariant QSslSocket::socketOption(QAbstractSocket::SocketOption option)

Returns the value of theoption option.

This function was introduced in Qt 4.6.

See alsosetSocketOption().

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.

The SSL configuration also contains fields that can change with time without notice.

This function was introduced in Qt 4.4.

See alsosetSslConfiguration(),localCertificate(),peerCertificate(),peerCertificateChain(),sessionCipher(),privateKey(),ciphers(), andcaCertificates().

QList<QSslError> QSslSocket::sslErrors() const

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

See alsoconnectToHostEncrypted().

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

QSslSocket emits 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 thatQSslSocket is 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 callQSslSocket::ignoreSslErrors() from inside a slot connected to this signal. If you need to access the error list at a later point, you can callsslErrors() (without arguments).

errors contains one or more errors that preventQSslSocket from verifying the identity of the peer.

Note: You cannot useQt::QueuedConnection when connecting to this signal, or callingQSslSocket::ignoreSslErrors() will have no effect.

Note:SignalsslErrors is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:

connect(sslSocket,static_cast<void(QSslSocket::*)(constQList<QSslError>&)>(&QSslSocket::sslErrors),[=](constQList<QSslError>&errors){/* ... */ });

See alsopeerVerifyError().

[slot]void QSslSocket::startClientEncryption()

Starts a delayed SSL handshake for a client connection. This function can be called when the socket is in theConnectedState but still in theUnencryptedMode. 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 usingconnectToHostEncrypted() instead, which automatically performs the handshake.

See alsoconnectToHostEncrypted() andstartServerEncryption().

[slot]void QSslSocket::startServerEncryption()

Starts a delayed SSL handshake for a server connection. This function can be called when the socket is in theConnectedState but still inUnencryptedMode. 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 ofQTcpServer and reimplementQTcpServer::incomingConnection(). The returned socket descriptor is then passed toQSslSocket::setSocketDescriptor().

See alsoconnectToHostEncrypted() andstartClientEncryption().

[static]QList<QSslCipher> QSslSocket::supportedCiphers()

Returns the list of cryptographic ciphers supported by this system. This list is set by the system's SSL libraries and may vary from system to system.

See alsodefaultCiphers(),ciphers(), andsetCiphers().

[static]bool QSslSocket::supportsSsl()

Returns true if this platform supports SSL; otherwise, returns false. If the platform doesn't support SSL, the socket will fail in the connection phase.

[static]QList<QSslCertificate> QSslSocket::systemCaCertificates()

This function provides the CA certificate database provided by the operating system. The CA certificate database returned by this function is used to initialize the database returned bydefaultCaCertificates(). You can replace that database with your own withsetDefaultCaCertificates().

See alsocaCertificates(),defaultCaCertificates(), andsetDefaultCaCertificates().

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

Reimplemented fromQIODevice::waitForBytesWritten().

bool QSslSocket::waitForConnected(int msecs = 30000)

Waits until the socket is connected, ormsecs milliseconds, whichever happens first. If the connection has been established, this function returns true; otherwise it returns false.

See alsoQAbstractSocket::waitForConnected().

bool QSslSocket::waitForDisconnected(int msecs = 30000)

Waits until the socket has disconnected ormsecs milliseconds, whichever comes first. If the connection has been disconnected, this function returns true; otherwise it returns false.

See alsoQAbstractSocket::waitForDisconnected().

bool QSslSocket::waitForEncrypted(int msecs = 30000)

Waits until the socket has completed the SSL handshake and has emittedencrypted(), ormsecs milliseconds, whichever comes first. Ifencrypted() 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.

See alsostartClientEncryption(),startServerEncryption(),encrypted(), andisEncrypted().

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

Reimplemented fromQIODevice::waitForReadyRead().

[virtual protected]qint64 QSslSocket::writeData(constchar * data,qint64 len)

Reimplemented fromQIODevice::writeData().

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp