Page 1 of 1

How to create a Self-Signed SSL Certificate

How to create a Self-Signed SSL Certificate
   0

Sometimes we need a Certificate so we can encrypt and decrypt network communication, for example for all kinds of network devices (eg. NAS, IoT devices, local web server, etc).

Unfortunately, for some of these applications, we cannot obtain a legit certificate from a CA (Certificate Authority), due to certain limitations.
In this article I’ll show you how to create such a free Self-Signed (self-created) certificate yourself, for Windows, macOS and Linux.

I’ll also briefly point out limitations and potential problems that come with a Self-Signed certificate or CERT.




Overview

Why do we need a Certificate?

For encrypted network/Internet communication (SSL), we will need a so called CERT or Certificate – the “key” to our encryption.
Such a CERT can be self generated (a.k.a. self-signed), or obtained through a valid CA (Certificate Authority).

This is standard for websites that use HTTPS (one should probably not be using HTTP anymore anyway), but certificates are also used for example for SSH, or for signing applications (Code Signing).

In this article we will focus on generating a Self-Signed certificate for SSL (Tweaking4All also has a SSH example which shows the inner workings in more detail).

 Installation of certificates on web servers is specific for each web server, and will not be discussed in this article.

Why Self-Signed CERT, instead of a CERT issued by a CA?

Ideally we’d want a CA (Certificate Authority) signed certificate.
Unfortunately these are not always free (Let’s Encrypt is a very good and free service), and sometimes a Self-Signed certificate is only option.

For example, a certificate signed by a valid CA can only be created for a valid public domain, for example tweaking4all.com or google.com.
However, a CA signed certificate cannot be generated for an IP address (eg. 192.168.1.100) or a local domain (eg. mynas or mydlinkrouter).

Disadvantages of Self-Signed CERTs

Disadvantages of a Self-Signed SSL Certificate include that browsers will not like them (unless the user “blesses” the certificate to be valid in their Operating System or browser).

You can see this in your browser when it isn’t showing the usual indicators that your connection is secure and/or the certificate is valid.

A browser may even present an error message (“error_self_signed_cert”, “sec_error_untrusted_issuer”, “err_cert_authority_invalid”) and will potentially prevent access to the content unless you click the ”Accept Risk” or “Continue anyway” button.

Besides that hick-up, Self-Signed certificates can be sensitive for a man-in-the-middle attack, as a Self-Signed certificate can be generated by just about anyone. However, at home and for testing purposes this of course may not be an issue.

Self-Signed SSL Certificates still have advantages; they are free, still provide encryption, and as mentioned before, they are suitable for “in house” and testing purposes.
Again: Self-Signed certificates are far from ideal for anything public (straight on the Internet) – but they will work.

So if your device (web server for example) is going to be open to the Internet, you should probably use a valid CA issued certificate, assuming you will have a domain or subdomain pointing to your device, and not just an IP address.

Certificate files

To be able to use encryption, as seen with SSL, we need two items to make this work.
One (private/secret) item is needed to encrypt content, and one item (public) to decrypt content.
These cannot be the same, after all we want to make sure the received content comes from a certain source.

See also the SSH Login without a Password article for more detail on how this kind of encryption works.

The CERT File (private)

The “CERT” (.cert) file, or better said the key in that file, is used to Encrypt content.

This is also the reason why this file is private and should never be shared, and only located on your device or web-server so it can encrypt content.
Only the CERT file can be used to encrypt content.

This file can be opened with a text editor, and starts with -----BEGIN CERTIFICATE----- .

The KEY file (public)

This “KEY” (.key) file is needed to Decrypt a message or content. However the “KEY” cannot be used to encrypt content.

This is why this KEY is public, otherwise a receiving party would not be able to read the content.
If the KEY can decrypt the content, then we are reasonable sure the received content actually comes from the expected source.

This file resides on your device or web-server, so it can share this with whoever wants to get encrypted content from this device or web-server.

In other words: if we can decrypt the content with the KEY, then we know it was encrypted with CERT.

This file can also be opened with a text editor, and starts with -----BEGIN PRIVATE KEY-----  (confusing right?).

Other file formats

You may encounter other files when working with certificates, like for example these:

.PEM, .CRT, .CA-BUNDLE, .CER, .P7B, or .P7S files contain one or more certificate files, often provided to you by the Certificate Authority packed in (for example) a ZIP file.

You may also encounter .PFX files. This is a file format for storing several objects into a single file.
For SSL certificates a .PFX file contains, a certificate (CERT) and a matching key (KEY) for each object, and the file is typically protected with a password.

The required files depends a little on your setup, but CERT and KEY are quite common.

How to create a Self-Signed SSL Certificate

The short version for the impatient or experienced … 

Make sure OpenSSL is available on your system and run this one-liner (!):


openssl req -newkey rsa:1024 -x509 -sha256 -days 365 -out certificate.cert -keyout certificate.key -nodes -subj "/C=US/ST=WI/L=YourCity/O=YourOrganization/OU=YourOrganizationUnit/CN=mydevice/emailAddress=admin@example.com"

Modify the parameters, like key length, company name, location and such, to match your needs.

Online Service to Generate Self-Signed Certificates 

Although I’m not a fan of doing it this way, there is the option to use an online service to generate Self-Signed certificates.
For example this one at NameCheap.

In order to create Certificates we need a tool to generate these, in in this article we will use OpenSLL.
Depending on your Operating System, it is already installed or you will need to download it (it is free).

OpenSSL for Linux

I’m not a Linux expert, and the Linux distros I tested came standard with OpenSSL pre-installed.
For those Linux distros that do not come with OpenSSL: check your application package manager, as it will most likely be listed in there, or try the good old apt-get:


sudo apt-get install openssl

OpenSSL for macOS

macOS comes by default with OpenSSL (actually a variant of OpenSSL, called LibreSSL).
You can, in case Apple removes it, or you feel the need to have the latest and greatest version, consider using brew to install OpenSSL.

OpenSSL for Windows

Unfortunately Windows does not come with OpenSSL, and the OpenSSL website does not provide a precompiled binaries. So you’ll either have to compile OpenSSL from source or obtain a binary elsewhere. For windows (32- and 64-bit) there is a OpenSSL Wiki page that lists precompiled binaries, or you can go straight to slproweb.com.

 

Generating a Self-Signed Certificate

Since OpenSSL works pretty much the same on all 3 platforms, I did not have to write 3 individual paragraphs covering each individual Operating System.

Key Length Considerations 

These days the use of a 2048 bit key is quite common for a web server running something like Apache.

However if you intend to use the key on something smaller, like a microcontroller (the ESP8266 for example), then you may want to select a shorter key.
For example, for ESP8266 compatibility, the certificate should use SHA256 and the key length has to be either 512 or 1024 bits key. A 512 bits long key will make ESP8266 respond faster, but it is still considered a weak key. So if this is not slowing down your application too much, then please consider using a 1024 bits key.
Note: there appears to be a way to have the ESP32/ESP8266 generate a key as well – I have not yet tested this.

Networkname, Networkname.local or IP address ? 

OpenSSL allows you to use an IP address instead of the domain name.
However, I prefer the use of my device’s network name, which gives me a little flexibility when moving devices around.

For a networkname to work, it needs to be unique and you will need to make sure that your DHCP server (typically your router) gives your device an IP address, and that this router is also the primary DNS server. With certain devices, like a NAS for example, I prefer the use of a dedicated IP address, which can be set in the DHCP settings of your router, where one would link the MAC address of said device to a fixed IP address (this IP address should not be in the dynamic range of your DHPC of course).

To make sure the device network name works, you can test this with a simple PING from the command line prompt on your PC, eg. ping networkname  or ping networkname.local.

In my setup I found “networkname.local” to not always work all that well (probably a config issue on my end), so I use just the networkname (also in these examples). More information about the use of “.local” can be found on the .local domain Wiki page.

To create a certificate, we do need to collect some information first.

Note: all of this can be entered in one single line, or in an interactive fashion – I recommend doing all this interactive, but for certain scenarios a one-liner can be more useful.

Generating a new certificate will automatically generate two files: the CERT file and the KEY file. You will need both!

The output files (key and cert) will be stored in the currently active directory. This is why I recommend changing to the desired directory before opening OpenSSL.

Below a list of parameters we would need. The values are examples and some can be modified or even left out. More information on these parameters can be found in the OpenSSL documentation.

OpenSSL Certificate Parameters
Parameter example Purpose
-x509 X509 specific certificate
-newkey rsa:1024 -sha256 Using sha256, 1024 bits key, encryption
-keyout certificate.key output file for the KEY
-out certificate.cert output file for the CERT
-days 365 This certificate will be valid for 365 days
-nodes -subj "
/C=US
/ST=WI
/L=YourCity
/O=YourOrganization
/OU=YourOrganizationUnit
/CN=mydevice
/emailAddress=admin@example.com
"
Add nodes ( this one single line!);
C stands for your country code (2 character short name)
ST to indicate state or province
L should be your city or town
O for your “organization”
OU refers to your “organizational unit”
CN for the network name, domain name or IP address
emailAddress is the admins email address

Create a Certificate interactive in OpenSSL

After installing OpenSSL (if not already available), we need to open Terminal (Mac/Linux), Command Prompt (Windows), or Shell (Linux), so we can start OpenSSL from the command line.

Before doing opening OpenSSL, I’d recommend to go to a directory where you want the keys to appear, and after that execute openssl from the command line.
In the examples below I’ll assume you want both files to appear on your desktop, naturally you can select any directory you like.

 

Windows:

This will be something Windows users have to pay attention to.
For example in case the openssl.exe is located in "C:\Program Files\OpenSSL-Win64\bin\" then you’d need to call OpenSSL with "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" .

(replace username with your username if you decide to use the same location)


cd C:\Users\username\Desktop
"C:\Program Files\OpenSSL-Win64\bin\openssl.exe"

This should result in something like this:


C:\Users\username\Desktop>"c:\Program Files\OpenSSL-Win64\bin\openssl.exe"
OpenSSL>

 

Mac and  Linux:

Mac and Linux users will most likely not even have to worry where the openssl binary is located, as it is typically already in the PATH environment variable.


cd ~/Desktop
openssl

Your should see a prompt like this:


13:44 ~ $ openssl
OpenSSL>

 

Now that OpenSSL is opened/started, type the following – keeping your preferences in mind, specifically how many days the certificate should be valid, key length, and the names of the KEY and CERT files:


req -newkey rsa:1024 -x509 -sha256 -days 365 -nodes -out certificate.cert -keyout certificate.key

After pressing Enter , OpenSSL will start it’s interactive part, asking for some additional (node) information like country code, city, organization, domain name, etc.
Here an example what this could look like:

Note: “Common Name” should be the domain, or the network name, or an IP address.


OpenSSL> req -newkey rsa:1024 -x509 -sha256 -days 365 -nodes -out certificate.cert -keyout certificate.key
Generating a 1024 bit RSA private key
...............................................++++++
.........++++++
writing new private key to 'certificate.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) []:US
State or Province Name (full name) []:WI
Locality Name (eg, city) []:YourCity
Organization Name (eg, company) []:YourOrganization
Organizational Unit Name (eg, section) []:YourOrganizationUnit
Common Name (eg, fully qualified host name) []:mydevice
Email Address []:admin@example.com

Create a Certificate in one line

I prefer using the interactive method, but it does have its limitations.
For example, adding both domain and IP address, or using the certificate generation in an automated script.

Below the one liner for the same kind of certificate.
Note that this is not done in OpenSSL, rather straight from the command-line prompt.

Windows users may need to enter the full path to the openssl.exe.

All the elements we discussed before are here packed in one single line, which can be run straight from the command-line:


1
openssl req -newkey rsa:1024 -x509 -sha256 -days 365 -out certificate.cert -keyout certificate.key -nodes -subj "/C=US/ST=WI/L=YourCity/O=YourOrganization/OU=YourOrganizationUnit/CN=mydevice/emailAddress=admin@example.com"

In this line you can replace the network name, with domain name or IP address as well.

Additional Information and Options

What the CERT and KEY file may look like

Just to give you and idea what these 2 files will look like, here an example (you can open both files with a regular text-editor).

CERT example:


-----BEGIN CERTIFICATE-----
MIICvTCCAiYCCQCzQ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XjHnjXl61zSW8SOFJS3RbXpJNN2ERwy
c2JGRoYq/+ogGfaI1+kpCHR9puArmyRKyb7UDU9VPSFRqgqIIlcr/Maf61hsHlk3
fuCnAudpOKI3eN9wN4N/JsVFRsXxAgMBAAECgYApFsMGGfiRTAwoT8wNcLXNk1oX
nPJvLzNBTocKGJt1mi2osKiyW59trpKV1K8bukahyl6UubUIfNBOXq41dcvuvKGt
PzdZjB5bS8WMW2pQTvMZslASasl/iq1b42gDW9ZjpFlSDwsxIgeRlXaRnXhAbxfS
SGAHPQ9/pg4DoHlNsQJBANOSehNjdMUjej0XVYdIBc9SK9vOa3IE68JYXl6vG54B
gt0zvzaycM6r/Fsz2nRhVutbb3EiPPATxXkWfh85+LUCQQDLrsOOFm7C7BXIau8I
swBMpMDZNp8D7700LGXdCqsADm8oL8cW0Z5ZiOaxoGo7XvIKWa3+peNHfkKJIjC8
k0nNAkBBSsXzr9C8eftiWQ4jBp4MYh544hYUhOJBAsZ0z/Nk6rB5FVwgRCc+EKN7
feAf5F5PmdMlhdxqdp+Ng9x+RIS1AkEAobHkptjiJzX6ePeDOXm5BB9KxWWaSSq6
HkAcwaSlac8LqXB8cX4JYnTPBzYc/3L5XQQin+SbkHcIZQtSe3HGBQJBAM797OT1
u28IWQXaf8BQJfCEtCs7JXi7tQeHd5EeiypPcxD01A8uigZKNRTUdHiW+NO8oax9
EB1pe2EynfqY1EA=
-----END PRIVATE KEY-----

Optional: Verifying your Certificate (CERT and KEY)

In OpenSSL, you can also verify your newly generated files with this statement for the CERT file:


OpenSSL> x509 -in certificate.cert -text -noout

OpenSSL> x509 -in certificate.cert -text -noout
Certificate:
    Data:
        Version: 1 (0x0)
        Serial Number: 14460480843101545521 (0xc8adf2b63e68a431)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=WI, L=Yourcity, O=YourOrganization, OU=YourOrganizationUnit, CN=mydevice/emailAddress=admin@example.com
        Validity
            Not Before: Dec 12 13:45:17 2020 GMT
            Not After : Dec 12 13:45:17 2021 GMT
        Subject: C=US, ST=WI, L=Yourcity, O=YourOrganization, OU=YourOrganizationUnit, CN=mydevice/emailAddress=admin@example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:d3:68:fe:f3:eb:e7:50:8f:45:77:c9:97:82:42:
                    71:6a:c7:a0:82:c9:f3:ef:ed:74:94:40:d0:8f:64:
                    be:a0:63:c8:a8:e5:fb:8d:ff:e3:2a:9a:92:2b:50:
                    ba:8d:21:2c:e7:1a:ff:10:5a:78:40:64:ea:7f:fb:
                    07:7a:e0:5f:f6:47:45:72:91:96:5f:a4:da:22:69:
                    55:86:90:2e:39:2f:47:e6:d6:86:3d:21:dc:10:68:
                    35:32:90:e5:49:98:79:85:30:90:d4:02:60:ac:90:
                    77:cc:d9:61:a5:3e:c3:3f:85:b5:68:16:c8:33:41:
                    7c:bb:0b:b4:8e:55:7b:d0:c3
                Exponent: 65537 (0x10001)
    Signature Algorithm: sha256WithRSAEncryption
         19:6a:73:24:df:3e:e5:82:0b:24:97:50:4b:25:28:de:88:83:
         47:b0:86:ec:56:18:f0:f3:77:75:e5:92:12:f8:66:f3:91:af:
         7d:89:2d:a6:4d:81:ac:6a:d3:4a:c6:ab:6c:c4:90:8f:8d:4c:
         93:af:bc:75:ac:ee:c0:6b:12:48:3d:30:71:32:f5:01:c2:ce:
         92:bb:c9:50:e9:b6:44:4c:fe:c1:4e:f3:90:11:36:91:a2:31:
         ad:77:c6:e7:20:57:27:1e:32:02:f5:ff:63:49:53:b7:c8:0e:
         11:ce:09:d1:00:61:5b:1a:1f:f6:ab:14:1c:d1:da:00:16:4d:
         08:4e

And this statement for the KEY file:


OpenSSL> rsa -in certificate.key -check

OpenSSL> rsa -in certificate.key -check
RSA key ok
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDTaP7z6+dQj0V3yZeCQnFqx6CCyfPv7XSUQNCPZL6gY8io5fuN
/+MqmpIrULqNISznGv8QWnhAZOp/+wd64F/2R0VykZZfpNoiaVWGkC45L0fm1oY9
IdwQaDUykOVJmHmFMJDUAmCskHfM2WGlPsM/hbVoFsgzQXy7C7SOVXvQwwIDAQAB
AoGARrDDH5jwHfXqSqWz7bB98DCUMWeKE94Yr0IE+w262DLFdASC2vaHZUWOPsGd
v3cqZpSWWUeHEjEsYGL2G1ZPf5S1Np1WGKoI//Xh2TzJLmWRM+A4G3n7FzBOT5ji
qNMFI8k+DyqPkerM5C/8pOiBUzyyCNxc7NIQJ5QaannJZpECQQDtOQgMKdnuGPj5
HRWzT0dl6u3c3BZnR+51jBRV0fcb24cIOMaP6WwxQs0G5M34wnZmyKBhedswwkN2
4NLBWAxtAkEA5CTo2B/Xap1wMqKSGjhSUXCsyrP9uU9ztK5+MkOkeZqGh3X6JCQR
34NT1EDszTtE1VAzCb8J1LfUxw9T4viz7wJBAL53qCp7/+rYSi9aVu4dnWoLcuh+
Hc7XRnNDAaDWcN4BKS5Ex8kM1j3HMO90DpzJJl/ofj1FpeREVf7BDPcIRxECQQCh
HyACYpp0BTRTzlR4iAY61eRyU6OA2AfTNtiRDwx9hRA1YrCCDadBvzHY2PFkD9OR
As7It05uGFYBL2YDCbmpAkAXrXR8TKbhIGY/HCYSHJZHEzIZkN10cY0I0ndN7yxK
+KcvPk0F58H+cui7rDuEH343GBNEUhU8tst2WQGxoSkD
-----END RSA PRIVATE KEY-----

Creating additional file formats

PEM (2) files

In case you need PEM files for your device or server, then rest assured, your CERT and KEY files, as created in this article, are already in the correct format.
To get the PEM files, just add the “.pem” extension of the certificate.cert and certificate.key files.

However, if you got your files from elsewhere, you can check if the file’s content begins with “—–BEGIN” and is readable in a text editor (see the examples above).
If however the file seems binary, then you can convert it with OpenSSL with:


openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

PEM – CERT and KEY combined in one file

If your device or web server does not allow you to load two separate files (CERT and KEY), then you’ll need to glue both files together.
Either copy and paste the content of both files (CERT and KEY) into one file, or for example in macOS or Linux use:


cat server.crt server.key > certificatecombined.pem

PKCS#12 or PFX file

I have not had a use for PFX files yet, but I have heard of instances where one of these is needed.
After creating a CERT and KEY file, you can create a PFX file with OpenSSL as well.

PCKS#12 or PFX ?

The PKCS#12 and the PFX files are the same, just a different extension.
The PFX format is a binary format for storing the server certificate, any intermediate certificates, and the private key into a single encrypted file.
PFX files are usually found with the extensions .pfx and .p12..

Remember the Password!
 

When running this command, you will be prompted for a password. REMEMBER the password, you will need it at a later time.


openssl pkcs12 -export -out certificate.pfx -inkey certificate.key -in certificate.cert

The resulting file will look like gibberish in a text editor.

 

 

 

 

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are no comments yet.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.
Tweaking4All will never share your email address with others.