OpenSSL create self signed certificate Linux with example


Written By - admin

 

Advertisement

Steps required to create self signed certificate in Linux

The steps involved to generate self signed certificate include:

  • Generate private key server.key
  • Create Certificate Signing Request (CSR) server.csr
  • Sign the certificate signing request and generate self signed certificate server.crt

 

Install openssl

On RHEL/CentOS 7/8 you can use yum/dnf respectively while on Ubuntu use apt-get to install openssl rpm

NOTE:

On RHEL system you must have an active subscription to RHN or you can configure a local offline repository using which "yum" package manager can install the provided rpm and it's dependencies.
[root@centos8-1 ~]# yum -y install openssl

 

Create encrypted password file (Optional)

  • With openssl self signed certificate you can generate private key with and without passphrase.
  • If you use any type of encryption while creating private key then you will have to provide passphrase every time you try to access private key.
  • With the encrypted password file we can avoid entering the password when we create self signed certificate.

I have created a plain text file "mypass" with my "secret" passphrase

[root@centos8-1 ~]# echo secret > mypass

Using openssl enc I will encrypt mypass file and create an encrypted file mypass.enc

[root@centos8-1 ~]# openssl enc -aes256 -pbkdf2 -salt -in mypass -out mypass.enc
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:

As you see the content of the encrypted file is not readable any more. Now you can easily share this encrypted file to any user to generate ssl certificate

[root@centos8-1 ~]# cat mypass.enc
Salted__▒▒Y$▒V΃cQVȥ▒2ĺ)▒MS▒

To decrypt the encrypted password file, we use below command:

[root@centos8-1 ~]# openssl enc -aes256 -pbkdf2 -salt -d -in mypass.enc
enter aes-256-cbc decryption password:
secret

 

I will create a new directory to store my certificates

Advertisement
[root@centos8-1 certs]# mkdir /root/certs
[root@centos8-1 certs]# cd /root/certs

I have also copied my encrypted password file to /root/certs

[root@centos8-1 certs]# ls -l
total 8
-rw-r--r-- 1 root root   32 Apr  9 13:31 mypass.enc

 

Openssl create self signed certificate with passphrase

In this section I will share the examples to openssl create self signed certificate with passphrase but we will use our encrypted file mypass.enc to create private key and other certificate files.

 

Generate private key

  • We need to generate private key which will use in next steps to create Certificate Signing Request (CSR)
  • In this example we will create private key with 3DES encryption.
  • You can also choose any other encyption.
[root@centos8-1 certs]# openssl genrsa -des3 -passout file:mypass.enc -out server.key 4096
Generating RSA private key, 4096 bit long modulus (2 primes)
................................................++++
..++++
e is 65537 (0x010001)

HINT: In this example I have used -passout with file:<filename>, but you can also use pass:<passphrase>, env:<variable>, fd:<number>. You can read more about these options: Network Security with OpenSSL. if you do not use -passout option, openssl generate private key command would prompt for the passphrase before generating private key.

 

Create Certificate Signing Request (CSR) certificate

Next create a certificate signing request (server.csr) using the openssl private key (server.key).

This command will prompt for a series of things (country, state or province, etc.). Make sure that "Common Name" matches the registered fully qualified domain name of your Linux server (or your IP address if you don't have one). Alternatively you can also create SAN certification which will allow you to provide multiple Alternative Names in a single certificate.

[root@centos8-1 certs]# openssl req -new -key server.key -out server.csr -passin file:mypass.enc
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) [XX]:IN
State or Province Name (full name) []:KARNATAKA
Locality Name (eg, city) [Default City]:BENGALURU
Organization Name (eg, company) [Default Company Ltd]:GoLinuxCloud
Organizational Unit Name (eg, section) []:R&D
Common Name (eg, your name or your server's hostname) []:centos8-1
Email Address []:admin@golinuxcloud.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

 

(Optional) To automate this step to create CSR (server.csr) we can either use openssl.cnf or create one configuration file with required input as I have shown below:

[root@centos8-1 certs]# cat self_signed_certificate.cnf
[req]
distinguished_name = req_distinguished_name
prompt = no
[req_distinguished_name]
C = IN
ST = Karnataka
L = Banaglore
O = GoLinuxCloud
OU = SDM
CN = centos8-1

Now to create CSR using this config file (If you have already created server.csr then you can ignore this):

[root@centos8-1 certs]# openssl req -new -key server.key -out server.csr -passin file:mypass.enc -config self_signed_certificate.cnf

Here we are using -config to take input from self_signed_certificate.cnf file. But make sure you change CN value based on your server hostname.

 

Create self signed certificate using openssl x509

  • The openssl x509 command is a multi purpose certificate utility.
  • It can be used to display certificate information, convert certificates to various forms, sign certificate requests like a "mini CA" or edit certificate trust settings
  • The last step to create self signed certificate is to sign the certificate signing request.
  • In this example the openssl certificate will last for 365 days.
  • We will use use our private key "server.key" with "server.csr" to sign the certificate and generate self signed certificate server.crt
[root@centos8-1 certs]# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt -passin file:mypass.enc
Signature ok
subject=C = IN, ST = Karnataka, L = Banaglore, O = GoLinuxCloud, OU = SDM, CN = centos8-1
Getting Private key

So our our openssl generate ssl certificate commands were successful and we have our self signed certificate server.crt

 

Openssl verify certificate content

In this article we have create below certificates

  • server.key ⇒ Private Key
  • server.csr ⇒ Certificate Signing Request
  • server.crt ⇒ Self-signed certificate

You can view the content of self signed certificate and other files using openssl:

# openssl rsa -noout -text -in server.key
# openssl req -noout -text -in server.csr
# openssl x509 -noout -text -in server.crt

 

Openssl self signed certificate without passphrase

In this section I will share the examples to create openssl self signed certificate without passphrase.
All the commands and steps will remain the same as we used above to generate self signed certificate, the only difference would be that we will not use any encryption method while we create private key in step 1

 

Openssl generate private key

In this example with openssl genrsa we will not use any encryption:

[root@centos8-1 certs]# openssl genrsa -out server-noenc.key 4096
Generating RSA private key, 4096 bit long modulus (2 primes)
................................................................++++
...................................................................................................++++
e is 65537 (0x010001)

As expected the openssl generate private key was executed without prompting for any passphrase.

 

Create certificate Signing Request (CSR) certificate

Next we will create CSR certificate using our private key. Again make sure you provide proper Common Name value and it should match the hostname/FQDN of your server's detail where you plan to use this certificate.

[root@centos8-1 certs]# openssl req -new -key server-noenc.key -out server-noenc.csr
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) [XX]:IN
State or Province Name (full name) []:KARNATAKA
Locality Name (eg, city) [Default City]:BENGALURU
Organization Name (eg, company) [Default Company Ltd]:GoLinuxCloud
Organizational Unit Name (eg, section) []:R&D
Common Name (eg, your name or your server's hostname) []:centos8-1
Email Address []:admin@golinuxcloud.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

To automate this step again you can create a configuration file as we created in this step....

 

Create self signed certificate using openssl x509

Now in the last step using openssl x509 we will create and sign our certificate using server-noenc.key and server-noenc.csr

[root@centos8-1 certs]# openssl x509 -req -days 365 -in server-noenc.csr -signkey server-noenc.key -out server-noenc.crt
Signature ok
subject=C = IN, ST = KARNATAKA, L = BENGALURU, O = GoLinuxCloud, OU = R&D, CN = centos8-1, emailAddress = admin@golinuxcloud.com
Getting Private key

 

Openssl verify certificate content

In this article we have create below certificates

  • server-noenc.key ⇒ Private Key
  • server-noenc.csr ⇒ Certificate Signing Request
  • server-noenc.crt ⇒ Self-signed certificate

You can view the content of self signed certificate and other files using openssl:

# openssl rsa -noout -text -in server-noenc.key
# openssl req -noout -text -in server-noenc.csr
# openssl x509 -noout -text -in server-noenc.crt

 

Setup Apache with self signed certificate

After you create self signed certificates, you can these certificate and key to set up Apache with SSL (although browser will complain of insecure connection).

Transfer server.crt and server.key to your Apache server and then define below values inside Virtual Hosting of /etc/https/conf/httpd.conf file

SSLEngine On
SSLCertificateFile /path/to/server.crt
SSLCertificateKeyFile /path/to/server.key

Next restart your httpd service and now you can use your Apache over HTTPS. But this is not considered secure and you should configure server client certificates to set up Apache with SSL for end to end encryption.

 

Lastly I hope the steps from the article to openssl create self signed certificate Linux was helpful. So, let me know your suggestions and feedback using the comment section.

 

Related Searches: How to generate self signed certificate using openssl in Linux. Install SSL certificate CentOS 7. Install root certificate linux. Centos 7 certificate authority.  Where are certificates stored in Red Hat or centOS 7 Linux. Create self signed certificate in Red Hat Linux. Create self signed certificate CentOS 7. CentOS trust self signed certificate. Install SSL certificate Red Hat 7. Create self signed certificate Red Hat Linux or CentOS 7. openssl generate self signed certificate sha256 CentOS. Generate self signed certificate from CSR. Generate private key from CRT. Install SSL certificate Linux.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

10 thoughts on “OpenSSL create self signed certificate Linux with example”

  1. I wonder: In creating the CA, you do
    (umask 077; openssl genrsa 1024 > serverkey.pem)
    but isn’t this part of creating a server request?. If you are to sign request made by others, there is no access to this data. (in case of self-signed, it doesn’t matter, otherwise it is)

    Reply
  2. I’m confused about the encrypted password part. The -passin and -passout options are for pass phrases, and do not support binary keys. They stop at the first newline character, which could easily appear in the output binary file when you do openssl enc. So even though this may appear to work, the actual pass phrase used to encrypt your private key may be unexpectedly short.

    I may be wrong, but I think you’d have to pass the decrypted data to -passin and -passout.

    If you run this command to try and verify your server private key, you’ll see it is not, in fact, encrypted with the secret pass phrase (which was “secret”):
    openssl rsa -noout -text -in server.key -passin pass:secret
    Yes, using -passin file:mypass.enc will successfully open the key, but the point is that the pass phrase is some unknown set of characters, ending at the first newline character.

    Reply
    • Hi Ron, This is a good observation, somehow even I didn’t noticed may be because I assumed it will work the other way. Let me check this and get back to you

      Reply
      • I missed to respond. I had checked this and this seems to be expected behaviour.
        You are not giving a plain text password instead you are giving an encrypted password so openssl will treat it as incorrect password. Have confirmed it with the developers.

        Reply
        • I’m not sure how to interpret that last response. Does this mean the whole approach is flawed and therefore the topic is pointless?

          Meanwhile I’m confused about the step “enter aes-256-cbc encryption password:” when first creating the .enc file. Was anything entered here for a password? When I left it blank no encrypted file was output. However if its not blank then won’t the entered value be required every time

          Reply
          • I am not sure if I understand your first question

            Regarding the empty passphrase. If you choose aes256, des3 or similar algorithm for your private key then it becomes mandatory to provide a passphrase which will be used to encrypt the private key. Here empty passphrase is not allowed. And yes if you give passphrase, during any connection which requires private key (mTLS) then before the authentication you will have to provide the password to decrypt the key before using. This depends on end user’s requirement to choose to use a secure or non-secure key.

            Reply
  3. Create self-signed certificate – Ubuntu
    This tutorial assumes that you know how to configure an apache2 server, the virtual host configuration file, and an index.html file.
    Part one
    Install the openssl (sudo apt-get install -y openssl). After installing the openssl – there were two directories created certs and private in addition to files.

    $sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/server.key -out /etc/ssl/certs/server.crt
    Please fill in the pop-up form and feel free to experiment:
    Country Name (2 letter code) [AU]:AU
    State or Province Name (full name) [Some-State]:Victoria
    Locality Name (eg, city) []: Melbourne
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Liqustra Pty Ltd
    Organizational Unit Name (eg, section) []:IT Department
    Common Name (e.g. server FQDN or YOUR name) []:server IP address or domain name
    Email Address []:your email address

    By this command we generated two files, server.key in the private folder and server.crt in the certs folder (you can give any name you want in the command).
    Please note: You have to have the execute permission to the private directory/folder.

    To allow permission, just type this command.

    sudo chmod +x private

    We must modify the openssl’s “default-ssl.conf” file.
    Default location in apache2:

    $sudo nano /etc/apache2/sites-available/default-ssl.conf
    Below is the default configuration:
    SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

    We need to change the default file, such as ssl-cert-snakeoil.pem and ssl-cert-snakeoil.key by server.crt and server.key.

    Apply this command:

    $sudo a2enmod ssl
    $sudo systemctl reload apache2

    Part Second
    Configure the virtual host configuration file.

        ServerAdmin admin@liqustra.com
        ServerName liqustra.com
        ServerAlias www.liqustra.com
        DocumentRoot /var/www/liqustra.com
       SSLEngine on
       SSLCertificateFile  /etc/ssl/certs/server.crt
       SSLCertificateKeyFile /etc/ssl/private/server.key
    
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined

    Part Three
    Open Firefox in the Ubuntu machine.
    Type: https://IP Address or domain name
    You will get warning sign, because it is a private certificate. Any way for now do the practice and you will be able to access the website by protocol https, instead of http.


    The self-signed certificate is authenticated by Firefox in my case, because I open the website several times.

    Part Four
    Troubleshooting. You can use the following command if you face any problem.

    $sudo apache2ctl configtest

    This command will show you the options. Reconfigure and reload the apache2, if needed start the apache2 again.
    Test case: if you want to remove openssl

    sudo apt-get remove -y openssl
    Reply
  4. I used to allow SSL on Ubuntu vsftpd FTP Server for connecting my Canon camera on it. This command line was working fine before version 3 of OpenSSL.

    $ sudo openssl req -x509 -nodes -days 40000 -newkey rsa:4096 -keyout /etc/ssl/private/vsftpd.key -out /etc/ssl/private/vsftpd.pem -extensions eos5d4

    It’s still working however when trying to connect to my FTP SSL enabled Server with FileZilla I get the following Error Message :

    Error:	GnuTLS error -48: Key usage violation in certificate has been detected.

    Running this command I get

    $ echo | openssl s_client -connect google.com:443 2>/dev/null | openssl x509 -noout -text | grep -i -A1 usage
                X509v3 Key Usage: critical
                    Digital Signature
                X509v3 Extended Key Usage: 
                    TLS Web Server Authentication
    $ 

    Meaning probably the flag Server Auth isn’t there (by default I guess).

    I have read in various places that I need a configuration file. I have used one found on this website like :

    [ req ]
    distinguished_name  = req_distinguished_name
    policy              = policy_match
    x509_extensions     = user_crt
    req_extensions      = v3_req
    
    [ req_distinguished_name ]
    countryName                     = Country Name (2 letter code)
    countryName_default             = AU
    countryName_min                 = 2
    countryName_max                 = 2
    stateOrProvinceName             = State or Province Name (full name) ## Print this message
    stateOrProvinceName_default     = 
    localityName                    = Locality Name (eg, city) ## Print this message
    localityName_default            = 
    0.organizationName              = Organization Name (eg, company) ## Print this message
    0.organizationName_default      = 
    organizationalUnitName          = Organizational Unit Name (eg, section) ## Print this message
    organizationalUnitName_default  = Admin ## This is the default value
    commonName                      = Common Name (eg, your name or your server hostname) ## Print this message
    commonName_max                  = 64
    emailAddress                    = Email Address ## Print this message
    emailAddress_max                = 64
    
    [ user_crt ]
    nsCertType              = client, server, email
    nsComment               = "OpenSSL Generated Certificate"
    subjectKeyIdentifier    = hash
    authorityKeyIdentifier  = keyid,issuer
    
    [ v3_req ]
    basicConstraints        = CA:FALSE
    extendedKeyUsage        = serverAuth, clientAuth, codeSigning, critical, emailProtection
    keyUsage                = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyCertSign, keyAgreement
    
    However adding a -config openssl.cnf to the above command fails. With :
    
    req: Use -help for summary.

    So is there a simple way out of this situation ? I have just upgraded to Ubuntu 22.04 which sports this openssl v3.

    Reply
    • You can create a custom file with below content

      # cat client_cert_ext.cnf
      basicConstraints = CA:FALSE
      nsCertType = client, email
      nsComment = "OpenSSL Generated Client Certificate"
      subjectKeyIdentifier = hash
      authorityKeyIdentifier = keyid,issuer
      keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
      extendedKeyUsage = clientAuth, emailProtection

      and pass this using -extfile

      openssl x509 -req -in client.csr -CA  -CAkey  -out client.cert.pem -CAcreateserial -days 365 -sha256 -extfile client_cert_ext.cnf
      Reply

Leave a Comment