openssl

From RaySoft

The openssl program is a command line tool for using the various cryptography functions of OpenSSL's crypto library from the shell. It can be used for

  • Creation and management of private keys, public keys and parameters
  • Public key cryptographic operations
  • Creation of X.509 certificates, CSRs and CRLs
  • Calculation of Message Digests
  • Encryption and Decryption with Ciphers
  • SSL/TLS Client and Server Tests
  • Handling of S/MIME signed or encrypted mail
  • Time Stamp requests, generation and verification[1]

Documentation

Subcommands & Parameters

ca[2]
The ca command is a minimal CA application. It can be used to sign certificate requests in a variety of forms and generate CRLs it also maintains a text database of issued certificates and their status.
-batch
This sets the batch mode. In this mode no questions will be asked and all certificates will be certified automatically.
-config FILE
Specifies the configuration FILE to use.
-days NUMBER
The NUMBER of days to certify the certificate for.
-extensions SECTION
The SECTION of the configuration file containing certificate extensions to be added when a certificate is issued (defaults to x509_extensions unless the -extfile option is used). If no extension section is present then, a V1 certificate is created. If the extension section is present (even if it is empty), then a V3 certificate is created.
-in FILE
An input FILE containing a single certificate request to be signed by the CA.
-out FILE
The output FILE to output certificates to. The default is standard output. The certificate details will also be printed out to this file in PEM format (except that -spkac outputs DER format).
-passin ARG
The key password source. For more information about the format of ARG see the Password Phrase Arguments section.
-revoke FILE
A FILE containing a certificate to revoke.
-subj NAME
Supersedes subject NAME given in the request. The NAME must be formatted as /type0=value0/type1=value1/..., characters may be escaped by \ (backslash), no spaces are skipped.
ciphers[3]
The ciphers command converts textual OpenSSL cipher lists into ordered SSL cipher preference lists. It can be used as a test tool to determine the appropriate cipherlist.
-v
Verbose option. List ciphers with a complete description of protocol version (SSLv2 or SSLv3; the latter includes TLS), key exchange, authentication, encryption and mac algorithms used along with any key size restrictions and whether the algorithm is classed as an export cipher.
dgst[4]
The digest functions output the message digest of a supplied file or files in hexadecimal. The digest functions also generate and verify digital signatures using message digests.
The generic name, dgst, may be used with an option specifying the algorithm to be used. The default digest is sha256. A supported digest name may also be used as the command name. To see the list of supported algorithms, use the list --digest command.
-digest NAME
Specifies NAME of a supported digest to be used.
-out FILE
FILE to output to, or standard output by default.
-r
Output the digest in 'coreutils' format.
dhparam[5]
This command is used to manipulate DH parameter files.
-out FILE
This specifies the output FILE. Standard output is used if this option is not present. The output file should not be the same as the input file.
enc[6]
The symmetric cipher commands allow data to be encrypted or decrypted using various block and stream ciphers using keys based on passwords or explicitly provided. Base64 encoding or decoding can also be performed either by itself or in addition to the encryption or decryption.
-a, -base64
Base64 process the data. This means that if encryption is taking place the data is Base64 encoded after encryption. If decryption is set then the input data is Base64 decoded before being decrypted.
-d
Decrypt the input data.
-e
Encrypt the input data: this is the default.
-in FILE
The input FILE, standard input by default.
-out FILE
The output FILE, standard output by default.
-salt
Use salt (randomly generated or provide with -S option) when encrypting, this is the default.
genpkey[7]
The genpkey command generates a private key.
-algorithm ALGORITHM
Public key ALGORITHM to use such as RSA, DSA or DH. If used this option must precede any -pkeyopt options.
-CIPHER
This option encrypts the private key with the supplied cipher e.g. -aes-256-cbc
-out FILE
Output the key to the specified FILE. If this argument is not specified then standard output is used.
-pass ARG
The output file password source. For more information about the format of ARG see the Password Phrase Arguments.
-pkeyopt OPTION:VALUE
Set the public key algorithm OPTION to VALUE. The precise set of options supported depends on the public key algorithm used and its implementation.
rand[8]
The rand command outputs num pseudo-random bytes after seeding the random number generator once.
-base64
Perform Base64 encoding on the output.
req[9]
The req command primarily creates and processes certificate requests in PKCS#10 format. It can additionally create self signed certificates for use as root CAs for example.
-days NUMBER
When the -x509 option is being used this specifies the NUMBER of days to certify the certificate for, otherwise it is ignored. NUMBER should be a positive integer. The default is 30 days.
-digest DIGEST
This specifies the message DIGEST to sign the request. Any digest supported by the dgst command can be used. This overrides the digest algorithm specified in the configuration file.
-key FILE
This specifies the FILE to read the private key from.
-keyform PEM|DER
The format of the private key file specified in the -key argument. PEM is the default.
-new
This option generates a new certificate request. It will prompt the user for the relevant field values.
If the -key option is not used it will generate a new RSA private key using information specified in the configuration file.
-out FILE
This specifies the output FILE to write to or standard output by default.
-outform PEM|DER
This specifies the output format, the options have the same meaning as the -inform option.
-passout ARG
The output file password source. For more information about the format of ARG see the Password Phrase Arguments.
-subj STRING
Sets subject name for new request or supersedes the subject name when processing a request. The STRING must be formatted as /type0=value0/type1=value1/..., characters may be escaped by \ (backslash), no spaces are skipped.
-x509
This option outputs a self signed certificate instead of a certificate request. This is typically used to generate a test certificate or a self signed root CA. The extensions added to the certificate (if any) are specified in the configuration file.
rsa[10]
The rsa command processes RSA keys. They can be converted between various forms and their components printed out.
-in FILE
This specifies the input FILE to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.
-out FILE
This specifies the output FILE to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.
s_client[11]
The s_client command implements a generic SSL/TLS client which connects to a remote host using SSL/TLS. It is a very useful diagnostic tool for SSL servers.
-CAfile FILE
A FILE containing trusted certificates to use during server authentication and to use when attempting to build the client certificate chain.
-connect HOST[:PORT]
This specifies the HOST and optional PORT to connect to. It is possible to select the host and port using the optional target positional argument instead. If neither this nor the target positional argument are specified then an attempt is made to connect to the local host on port 4433.
-ssl3, -tls1, -tls1_1, -tls1_2, -tls1_3
-no_ssl3, -no_tls1, -no_tls1_1, -no_tls1_2, -no_tls1_3
These options require or disable the use of the specified SSL or TLS protocols. By default s_client will negotiate the highest mutually supported protocol version. When a specific TLS version is required, only that version will be offered to and accepted from the server.
x509[12]
The 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.
-in FILE
This specifies the input FILE to read a certificate from or standard input if this option is not specified.
-inform PEM|DER
This specifies the input format normally the command will expect an X.509 certificate but this can change if other options such as -req are present.
-noout
This option prevents output of the encoded version of the request.
-text
Prints out the certificate in text form. Full details are output including the public key, signature algorithms, issuer and subject names, serial number any extensions present and any trust settings.

Password Phrase Arguments

Several commands accept password arguments, typically using -passin and -passout for input and output passwords respectively. These allow the password to be obtained from a variety of sources. Both of these options take a single argument whose format is described below.[1]

env:VARIABLE
Obtain the password from the environment VARIABLE. Since the environment of other processes is visible on certain platforms this option should be used with caution.
file:FILE
The first line of FILE is the password. If the same FILE argument is supplied to -passin and -passout arguments then the first line will be used for the input password and the next line for the output password. FILE need not refer to a regular file: it could for example refer to a device or named pipe.
fd:NUMBER
Read the password from the file descriptor NUMBER. This can be used to send the data via a pipe for example.
stdin
Read the password from standard input.

Examples

Generate a CA based on a RSA public/private key pair
install --backup --mode=0400 '/dev/null' 'ca.key'
openssl genpkey -algorithm 'RSA' -pkeyopt 'rsa_keygen_bits:4096' \
  -aes-256-cbc -out 'ca.key'
openssl rsa -text -noout -in 'ca.key'
openssl req \
  -new -x509 -sha256 -days 3650 \
  -subj '/C=CH/L=Zurich/O=RaySoft/CN=RootCA' \
  -key 'ca.key' -keyform 'PEM' \
  -out 'ca.crt' -outform 'PEM'
openssl x509 -text -noout -in 'ca.crt'
Generate a SubCA based on a RSA public/private key pair
echo -n > 'index.txt'
echo 01 > 'serial'
install --backup --mode=0400 '/dev/null' 'subca1.key'
openssl genpkey -algorithm 'RSA' -pkeyopt 'rsa_keygen_bits:4096' \
  -aes-256-cbc -out 'subca1.key'
openssl req \
  -new -sha256 -days 1825 \
  -subj '/C=CH/L=Zurich/O=RaySoft/CN=SubCA1' \
  -key 'subca1.key' -keyform 'PEM' \
  -out 'subca1.csr' -outform 'PEM'

/etc/ca/openssl.cnf

openssl ca \
  -config '/etc/ca/openssl.cnf' -batch \
  -in  'subca1.csr' \
  -out 'subca1.crt'
openssl x509 -text -noout -in 'subca1.crt'
Generate a certificate request with alternative domain names
install --backup --mode=0400 '/dev/null' 'raysoft.ch.key'
openssl genpkey -algorithm 'RSA' -pkeyopt 'rsa_keygen_bits:4096' \
  -aes-256-cbc -out 'raysoft.ch.key'

/etc/ca/openssl.cnf

openssl req \
  -new -sha256 -days 730 \
  -config '/etc/ca/openssl.cnf' -batch \
  -subj '/C=CH/L=Zurich/O=RaySoft/CN=raysoft.ch' \
  -key 'raysoft.ch.key' -keyform 'PEM' \
  -out 'raysoft.ch.csr' -outform 'PEM'
openssl req -text -noout -in 'raysoft.ch.csr'
Remove encryption from a private key
openssl rsa -in 'crypted.key' -out 'unencrypted.key'
Convert a private key from PEM to DER & from DER to PEM
openssl rsa \
  -in  'raysoft.ch.pem.key' -inform  'PEM' \
  -out 'raysoft.ch.der.key' -outform 'DER'
openssl rsa \
  -in  'raysoft.ch.der.key' -inform  'DER' \
  -out 'raysoft.ch.pem.key' -outform 'PEM'
Convert a certificate from PEM to DER & from DER to PEM
openssl x509  \
  -in  'raysoft.ch.pem.crt' -inform  'PEM' \
  -out 'raysoft.ch.der.crt' -outform 'DER'
openssl x509 \
  -in  'raysoft.ch.der.crt' -inform  'DER' \
  -out 'raysoft.ch.pem.crt' -outform 'PEM'
Get a Perfect forward secrecy optimized cipher suite
NOTE:
Remove all newlines!
openssl ciphers -v 'EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA EECDH+aRSA
                    EECDH HIGH !SSLv3 !SSLv2 !TLSv1 !aNULL !AESCCM !ARIA
                    !CAMELLIA !DSS !PSK'
| column -t

Output:

TLS_AES_256_GCM_SHA384         TLSv1.3  Kx=any   Au=any    Enc=AESGCM(256)             Mac=AEAD
TLS_CHACHA20_POLY1305_SHA256   TLSv1.3  Kx=any   Au=any    Enc=CHACHA20/POLY1305(256)  Mac=AEAD
TLS_AES_128_GCM_SHA256         TLSv1.3  Kx=any   Au=any    Enc=AESGCM(128)             Mac=AEAD
ECDHE-ECDSA-AES256-GCM-SHA384  TLSv1.2  Kx=ECDH  Au=ECDSA  Enc=AESGCM(256)             Mac=AEAD
ECDHE-ECDSA-AES128-GCM-SHA256  TLSv1.2  Kx=ECDH  Au=ECDSA  Enc=AESGCM(128)             Mac=AEAD
ECDHE-RSA-AES256-GCM-SHA384    TLSv1.2  Kx=ECDH  Au=RSA    Enc=AESGCM(256)             Mac=AEAD
ECDHE-RSA-AES128-GCM-SHA256    TLSv1.2  Kx=ECDH  Au=RSA    Enc=AESGCM(128)             Mac=AEAD
ECDHE-ECDSA-CHACHA20-POLY1305  TLSv1.2  Kx=ECDH  Au=ECDSA  Enc=CHACHA20/POLY1305(256)  Mac=AEAD
ECDHE-ECDSA-AES256-SHA384      TLSv1.2  Kx=ECDH  Au=ECDSA  Enc=AES(256)                Mac=SHA384
ECDHE-ECDSA-AES128-SHA256      TLSv1.2  Kx=ECDH  Au=ECDSA  Enc=AES(128)                Mac=SHA256
...
Encrypting or decrypting a file
if type -P 'openssl' >'/dev/null' 2>&1; then
  my::crypt() {
    if [[ -z "$1" || ! -f "$1" ]]; then
      echo "Usage: ${FUNCNAME} FILE"
      return 1
    fi

    local action=''
    local new_file=''
    local old_file="$1"
    local options=('-aes-256-gcm' '-salt')

    if [[ "${old_file}" =~ \.enc$ ]]; then
      new_file="${old_file%.enc}"
      options+=('-d')
      action='decrypt'
    else
      new_file="${old_file}.enc"
      options+=('-e')
      action='encrypt'
    fi

    if [[ -f "${new_file}" ]]; then
      my::carp "File should not be overwritten: ${new_file}"
      return 1
    fi

    if openssl enc "${options[@]}" -in "${old_file}" \
         -out "${new_file}" >'/dev/null' 2>&1; then
      echo "${action^} '${old_file}' to '${new_file}'"

      rm "${old_file}"
    else
      my::carp "Error ${action}ing file: ${old_file}"
      return 1
    fi
  }
fi
Base64 encoding & decoding
openssl enc -base64 <<<'MyText'

Output:

TXlUZXh0Cg==
openssl enc -base64 -d <<<'TXlUZXh0Cg=='

Output:

MyText
Create a file's digist
openssl dgst -sha256 '/etc/passwd'

Output:

SHA256(/etc/passwd)= d2d98504640a1bfd348be3403641dea5d31079d861d09da0ffc2f80f011c7937
Create Diffie Hellman parameters
openssl dhparam -out 'dh4096.pem' 4096
NOTE:
Use Diffie Hellman parameters to hardening the TLS connections![13]
Create a 10 bytes long random password based on the Base64 charset [a-zA-Z0-9/+]
openssl rand -rand '/dev/random' -base64 12 | cut --characters='1-10'

Output:

b5/FeVaFlWeS

References

  1. 1.0 1.1 man 1 'openssl'
  2. man 1 'ca'
  3. man 1 'ciphers'
  4. man 1 'dgst'
  5. man 1 'dhparam'
  6. man 1 'enc'
  7. man 1 'genpkey'
  8. man 1 'rand'
  9. man 1 'req'
  10. man 1 'ras'
  11. man 1 's_client'
  12. man 1 'x509'
  13. https://weakdh.org/sysadmin.html