How to generate a self-signed certificate using OpenSSL

2 min read | by Jordi Prats

Using openssl we can create a self-signed using a non interactive command suitable for automation if we give all the information at once such as the CN, and the days to expire

If we already have a private key we want to use, we can use it using the option -key. This command will create as a output the file server.crt containing the self-signed certificate:

openssl req -new -sha256 \
    -key server.key \
    -subj "/C=RC/ST=Barcelona/O=pet2cattle/CN=pet2cattle.com" \
    -nodes -x509 \
    -days 365 \
    -out server.crt

But we can also tell openssl to also create a private key for us

openssl req -new -sha256 \
    -newkey rsa:2048 \
    -subj "/C=RC/ST=Barcelona/O=pet2cattle/CN=pet2cattle.com" \
    -nodes -x509 \
    -days 365 \
    -out server.crt

These days is quite common to also need to have a SAN record on the certificate, starting from OpenSSL 1.1.1 if got much easier to do it:

openssl req -new -sha256 \
    -key server.key \
    -subj "/C=RC/ST=Barcelona/O=pet2cattle/CN=pet2cattle.com" \
    -nodes -x509 \
    -days 365 \
    -out server.crt \
    -addext "subjectAltName = DNS:pet2cattle.com"

Posted on 21/05/2021