Self-signed certificates with OpenSSL

Certificates signed by recognized authorities are essential to establish the chain of trust needed for public websites. However, it is much easier to obtain a self-signed certificate for testing or development.

It is also acceptable to use a self-signed certificate for certain private applications where the client can be deployed with a copy of the certificate, and trust only that certificate. This is called certificate pinning. Indeed, when used properly, certificate pinning can be more secure than using a certificate authority. However, it is not appropriate for public-facing websites.

We require a certificate to test our HTTPS server. We use a self-signed certificate because they are the easiest to obtain. The downside to this method is that web browsers won't trust our server. We can get around this by clicking through a few warnings in the web browser.

OpenSSL provides tools to make self-signing certificates very easy.

The basic command to self-sign a certificate is as follows:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout key.pem 
-out cert.pem -days 365

OpenSSL asks questions about what to put on the certificate, including the subject, your name, company, location, and so on. You can use the defaults on all of these as this doesn't matter for our testing purposes.

The preceding command places the new certificate in cert.pem and the key for it in key.pem. Our HTTPS server needs both files. cert.pem is the certificate that gets sent to the connected client, and key.pem provides our server with the encryption key that proves that it owns the certificate. Keeping this key secret is imperative.

Here is a screenshot showing the generation of a new self-signed certificate:

You can also use OpenSSL to view a certificate. The following command does this:

openssl x509 -text -noout -in cert.pem

If you're on Windows using MSYS, you may get garbled line endings from the previous command. If so, try using unix2dos to fix it, as shown by the following command:

openssl x509 -text -noout -in cert.pem | unix2dos

Here is what a typical self-signed certificate looks like:

Now that we have a usable certificate, we are ready to begin our HTTPS server programming.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.159.19