Back to Blog home

SSL with 5 lines of code ;-)

Published on Monday March 26, 2007 by Andreas Aardal Hanssen in Qt | Comments

Gah... I'm currently working hard to finish QSslSocket, need to get it 100% rock solid before the 4.3.0 release. It's tough; OpenSSL isn't the easiest toolkit to deal with, but then again, the API that Qt 4.3 provides is looking so good that it's all going to be worth it (/me tries to comfort himself).

For example, take a look at this little well-known snippet of code. It's a stub for a Qt Console application, one of my favorite templates for writing nice little command line tools:

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
}

Now, with 5 lines of code, we'll add a QSslSocket that downloads PayPal's front page using HTTPS. Don't take these very few lines lightly; although you cannot see any certificates/keys/ciphers or anything, this code is as secure as SSL can get. And as is typical for Qt, it's so easy to do that you'd want to add SSL to all your networking ;-).

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

QSslSocket socket;
socket.connectToHostEncrypted("www.paypal.com", 443);
socket.write("GET / HTTP/1.0rnrn");
while (socket.waitForReadyRead())
qDebug() << socket.readAll().data();
}

QSslSocket::connectToHostEncrypted() is a special version of connectToHost() that auto-initiates a client side hand shake after the connection has been established. QSslSocket uses the system's default CA bundle (or, in lack of such a bundle, it uses a built-in bundle). And if anything goes wrong with the SSL handshake (i.e., the host identity is not established), the connection will be torn down, and the first waitForReadyRead() call will fail before any data is transmitted. Is that sweet, or what. ;-)

Now let's take this a step further. Say you want to use one of the public proxy servers available. Ever been worried that these proxies can intercept your transmission? Well with QSslSocket, you no longer need to worry. Add one line to the above script to use an HTTP CONNECT proxy:

    QSslSocket socket;
socket.setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, "130.226.169.133", 3128));
...

Now, your 5-liner has become a 6-liner, with a fully-secured connection over an HTTP proxy (disclaimer: I have no clue who owns that proxy, I just know whomever it is cannot decrypt the transmission!).

Subscribe to Our Blog

Stay up to date with the latest marketing, sales and service tips and news.

The blog comment system has been migrated to a new platform. If you face any issues, please let us know via feedback@qt.io.