Skip to content
Search

OpenSSL

lastmod 2025-02-14created 2014-04-1694 edits

OpenSSL is an open-source implementation of TLS and SSL, protocols used for data communication over a network. Its core library, written in C, implements basic cryptographic functions and various utility functions.

Category

Password security

Algorithms

E.T.C

Libraries

Terms/Formats

Certificates used to ensure security over the internet come in several formats. The following is a quick description of the different types of certificates.

Abstract Syntax Notation One (ASN.1)
Abstract syntax notation; a protocol that defines data exchange over a network
Basic Encoding Rules (BER; .ber)
The BER (Basic Encoding Rules) format is one of the encoding formats defined as part of the ASN.1 standard. It is a standard for encoding abstract information into a concrete data stream. BER and its two subsets, DER (Distinguished Encoding Rules) and CER (Canonical Encoding Rules).
Certificate Authority (CA)
Certificate authority
Certificate File (.crt, .cer)
CRT - Security Certificate File Format
security CeRTificate file, abbreviated as crt.
A file with the .crt or .cer extension contains a single X.509 certificate using DER (Distinguished Encoding Rules), a set of rules defined by the ASN.1 standard for specifying the format of binary data.
Attached to mean "this is a certificate file"; almost always PEM format, and an extension mainly used on Unix/Linux-based systems. The cer extension is also used sometimes. (Rather than the .crt extension, .pem or .der is recommended so the file format is clear)
.cer files are mostly PEM format, sometimes binary format, and the extension is mainly used on Windows-based systems to mark a file as a certificate file. It means almost the same as the crt extension, and both the cer and crt extensions are recognized by default on Windows. It depends on which format was used when saving, and naming is up to the file creator.
Certificate Revocation List (CRL) / Online Certificate Status Protocol (OCSP)
Standards/methods for checking certificate validity
Certificate Signing Request (CSR; .csr)
Almost always PEM format. An extension attached to mark a request file whose contents are submitted to a certificate authority (CA) to apply for SSL issuance. (Base64 text file)
Distinguished Encoding Rules (DER) .der
The DER (Distinguished Encoding Rules) format is used in cryptography to guarantee that data that must be digitally signed, such as X.509 certificates, produces a unique marker with a unique serial number. The DER format makes signing and verifying X.509 certificates possible.
Short for Distinguished Encoding Representation (DER); a binary format. Its contents can only be checked through a certificate library that can read the binary encoding format. Apart from private or special fields such as finance and very old legacy systems, it is not a format commonly used in recent web server SSL systems. (binary file)
Elliptic Curve Digital Signature Algorithm (ECDSA)
A digital signature algorithm using elliptic curves
Java Key Store (.jks)
A proprietary Java-based certificate store format. Like pfx, it can hold private key + server certificate + root certificate + chain certificate together, so it is useful for managing SSL certificate files. The format most often used when applying SSL on the Java-based Tomcat server. (e.g., sslcert.co.kr_xxx.jks) (binary file) (jks and the like are not so much certificates as files used as a repository/store/basket that collects certificates)
Key File (.key)
An extension mainly used in openssl and java to mark a file as a private key file.
It may be PEM format or DER binary format; you have to open the file to know which format it is.
It depends on which format was used when saving, and the extension is up to whoever names it. (e.g., sslcert.co.kr_xxx.key.pem)
Privacy-enhanced Electronic Mail (Privacy Enhanced Mail, PEM)
.pem is Base64-encoded ASCII text. Alternatively, Privacy Enhanced Mail is a format for securing email using public key cryptography. It is a text-only encoding that allows use in S/MIME message headers. The .pem format is the base64 encoding of an X.509 certificate (binary DER format) surrounded by text headers.
The default format used in every SSL-related process, including private keys, server certificates, root certificates, chain certificates, and CSRs; the most widespread industry-standard format, compatible with almost 99% of systems. (mostly Base64 text files)
Public Key Cryptography Standards (PKCS)
Standard on the syntax for storing a Private Key
Uses PKCS#1, PKCS#8, PKCS#12, etc.
Public Key Cryptography Standard #7 (PKCS#7; .p7b, .p7c, .p7s)
A file with the .p7b extension contains a PKCS#7 (Public Key Cryptography Standard #7) message that includes one or more X.509 certificates. The S/MIME secure mail standard uses PKCS#7 for digitally signed and encrypted messages.
PKCS#7 format; it can hold 'server certificate + root certificate + chain certificate' together, so it is quite useful and convenient when applying or migrating SSL certificates. Windows recognizes it automatically, and some servers only accept certificate configuration in p7b format. (Base64 text file) (unlike pfx, p7b does not include the private key) (some use the .p7c extension) (e.g., sslcert.co.kr_xxx.p7b) (p7b and the like are not so much certificates as files used as a repository/store/basket that collects certificates)
Public Key Cryptography Standard #12 (PKCS#12; .p12, .pfx)
A file with the .p12 extension contains an encrypted file format that complies with PKCS#12 (Public Key Cryptography Standard #12). It is a portable format for storing or transporting a user's private keys, certificates, and other confidential information. This standard supports direct transfer of personal information under several privacy and integrity modes, ranging from public/private key use to the low security of password-based privacy protection.
A certificate store in PKCS#12 binary format, standing for Personal Information Exchange Format. Mainly used when applying/moving certificates on Windows IIS. Its main advantage is that it can hold the private key, server certificate, root certificate, and chain certificate together, so it is quite useful and convenient when applying or migrating SSL certificates. These days more and more servers, such as Tomcat, support pfx configuration. (e.g., sslcert.co.kr_xxx.pfx) (binary file) (pfx/p12 and the like are not so much certificates as files used as a repository/store/basket that collects certificates)
Public Key Infrastructure (PKI)
Public key infrastructure
Rivest–Shamir–Adleman (RSA)
A public-key cryptosystem
X.509
A PKI standard for using public key certificates and authentication algorithms

File extension storage patterns

  • By encoding
    • Distinguished Encoding Representation (DER; .der) - A kind of method for representing ASN.1. (stored as binary)
    • Privacy Enhanced Mail (PEM; .pem) - Base64-encoded ASCII text (used more often as the standard)
  • By content
    • Private Key (.key) - private key
    • Certificate (.cer mainly used on Windows, .crt mainly used on *NIX) - certificate
    • PKCS #12 (.p12, .pfx) - standard for storing a private key, certificate, etc. together in one file
    • Certificate Signing Request (.csr) - file for sending my private key signature to the CA to get a certificate issued
    • Serial (.srl) - file the CA uses to manage the Serial when issuing certificates

Extracting certificates

With openssl, you can print the SSL certificate of a server you connect to over HTTPS as below.

#!/usr/bin/env bash

if [[ -z $(which openssl) ]]; then
    echo "Not found openssl."
    exit 1
fi

SERVER_HOST=$1
SERVER_PORT=${2:-443}
if [[ -z $SERVER_HOST || -z $SERVER_PORT ]]; then
    echo "Usage: $0 {server_host} {server_port:443}"
    exit 1
fi

echo "QUIT" | openssl s_client -connect "$SERVER_HOST:$SERVER_PORT" 2>&1 | openssl x509 -inform PEM -text

Add the output to the CA list. Save the script above as get-server-certificate and run it as below.

## Ubuntu:
$ sudo ./get-server-certificate nexus.local > /etc/ssl/certs/nexus.local

How to register a trusted root certificate

See OpenSSL:X509#How to register a trusted root certificate.

Command-line example

Convert format

PEM -> DER
x509 -inform PEM -in 변환할파일명.pem -out 변환된파일명.der
DER -> CRT
x509 -inform DER -in 변환할 파일명.der -out 변환된파일명.crt

How to create a certificate

Notes on how to create certificates.

Self Signed Certificate bash script

A script that generates a private key (private.key) and a certificate (certificate.crt) in one go:

$ openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:4096 -keyout private.key -out certificate.crt -subj '/CN=localhost'

The certificate file can be read as below.

$ openssl x509 -text -noout -in certificate.crt

If you want to run it as a script, see below.

#!/bin/bash

echo "###########################################"
echo "## Generate Self Signed Certificate(SSC) ##"
echo "###########################################"

if [[ -z $(which openssl) ]]; then
    echo "Not found openssl."
    exit 1
fi

DAYS=36500 ## 100 years
KEYSIZE=2048
#KEYSIZE=4096
PRIVATE_KEY_FILE=$CERTS_DIR/onlyoffice.key
REQUEST_FILE=$CERTS_DIR/onlyoffice.csr
CERTIFICATE_FILE=$CERTS_DIR/onlyoffice.crt

COUNTRY=NO
STATE=NO
LOCATION=NO
ORGANIZATION=NO
ORGANIZATIONAL_UNIT=NO
COMMON_NAME=NO

## sets certificate subject
SUBJ="/C=${COUNTRY}/ST=${STATE}/L=${LOCATION}/O=${ORGANIZATION}/OU=${ORGANIZATIONAL_UNIT}/CN=${COMMON_NAME}"

## Create the server private key
openssl genrsa -out "$PRIVATE_KEY_FILE" $KEYSIZE

## Create the certificate signing request (CSR)
openssl req -new -sha256 -key "$PRIVATE_KEY_FILE" -out "$REQUEST_FILE" -subj "${SUBJ}"

## Sign the certificate using the private key and CSR
openssl x509 -req -sha256 -days $DAYS -in "$REQUEST_FILE" -signkey "$PRIVATE_KEY_FILE" -out "$CERTIFICATE_FILE"

## Check a certificate.
openssl x509 -in "$CERTIFICATE_FILE" -text -noout

echo Done.

Strengthening the server security

This section provides you with instructions to strengthen your server security. To achieve this you need to generate stronger DHE parameters.

$ openssl dhparam -out "$DHPARAM_FILE" 2048

How SSL works

Process_of_the_SSL_certificates.jpg

Generate a private key. Use AES rather than Triple DES (-des3).2

$ openssl genrsa -aes256 -out server.key 2048

Generate the signing request, a CSR (Certificate Signing Request) file.

$ openssl req -new -key server.key -out server.csr

Removing the password is optional. If you do not remove it, you have to enter the password whenever Httpd or the like needs to access the certificate (e.g., reboot).

$ openssl rsa -in server.key -out server.key.insecure

Generate a private certificate (CRT).

$ openssl x509 -req -days 1280 -in server.csr -signkey server.key -out server.crt

sigkey flag

When generating a private certificate, you pass the private key with the -signkey option, which may seem strange given that what a private authority requires in the certification process is the CSR file and the public key. This is explained in the manual page.

-signkey filename

    this option causes the input file to be self signed using the supplied private key.

    If the input file is a certificate it sets the issuer name to the subject name (i.e. makes it self signed) changes the public key to the supplied value and changes the start and end dates. ...

In other words, it creates the public key internally.

Config file

Hot to use API

Examples

openssl rsa -in key.pem -out keyout.pem
To remove the pass phrase on an RSA private key
openssl rsa -in key.pem -des3 -out keyout.pem
To encrypt a private key using triple DES
openssl rsa -in key.pem -outform DER -out keyout.der
To convert a private key from PEM to DER format
openssl rsa -in key.pem -text -noout
To print out the components of a private key to standard output
openssl rsa -in key.pem -pubout -out pubkey.pem
To just output the public part of a private key
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
Output the public part of a private key in RSAPublicKey format

Generate private key from an existing crt file

A simple example:

$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
       -keyout mysitename.key -out mysitename.crt

Generating RSA private and public keys

## 개인키:
$ openssl genrsa -out private.pem 1024

## 개인키를 이용한 공개키 생성:
$ openssl rsa -in private.pem -out public.key -pubout -outform derwriting RSA key
  • -des, -seed, -aes256, ...: Encrypts the key with the given method. No encryption if omitted
  • -passout pass:PASSWORD: Sets the password when encrypting the key. An input prompt appears if omitted
  • -f4 (0x10001), -3: Sets the E value. Default: -f4
  • 1024, 2048, 3072, 4096, ...: Private Key bit size.

Creating a CSR

openssl req -new -key key.pem -out my.csr
  • -md5, -sha1, -sha256, ...: Digest used for signing. The default varies by version; just use sha256. Full list: openssl dgst -h
  • -subj: Sets the certificate subject. Shows an input prompt if omitted
    • Example: -subj "/C=KR/O=sho/CN=SHO Certificate"
    • /C= - Country
    • /ST= - State; in Korea, the city/province
    • /L= - Location
    • /O= - Organization, company name
    • /OU= - Organization Unit, department name
    • /CN= - Common Name

Generating a certificate from a CSR

X.509 V3 extension settings (the ca.ext and end.ext files used below)

Web TLS certificate (for CA; ca.ext):

basicConstraints = critical, CA:TRUE
#basicConstraints = critical, CA:TRUE, pathlen:0

subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
keyUsage = cRLSign, keyCertSign

Web TLS certificate (End-entity; for the site; end.ext):

basicConstraints = critical, CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = DNS:blog.iolate.kr, IP:1.1.1.1

Generating the CA certificate:

openssl x509 -req -days 3650 -extfile ca.ext -signkey key.pem -in my.csr -out root.crt
  • -set_serial 1: Sets the serial value. A random value is generated if not set
  • -md5, -sha1, -sha256, ...: Digest used for signing. Full list: openssl dgst -h
    • Unless it is a Root CA you set trust for yourself, use sha256. Browsers warn when a weak digest such as sha1 is used

Generating the End-entity certificate:

openssl x509 -req -days 365 -extfile end.ext -CA root.crt -CAcreateserial -CAkey my.key -in my.csr -out end.crt
openssl x509 -req -days 365 -extfile end.ext -CA root.crt -CAserial root.srl -CAkey my.key -in my.csr -out end.crt
  • -CAcreateserial: Assigns the serial automatically and creates a serial file (.srl)
  • -CAserial root.srl: After issuing once with CAcreateserial, pass the serial file with this option
  • -md5, -sha1, -sha256, ...: Digest used for signing. Browsers warn when a weak digest such as sha1 is used

Checking generated file information

CSR / certificate / private key

openssl [req/x509/rsa] -noout -text -in [my.csr/end.crt/my.key]
openssl [req/x509/rsa] -noout -modulus -in [my.csr/end.crt/my.key] | openssl md5

File encryption

Private key file encryption

$ openssl aes-256-cbc -in secret.txt -out secret.txt.enc
$ openssl aes-256-cbc -d -in secret.txt.enc -out secret.txt

Check the list of Chipers with openssl --help.

Public key file encryption

Encrypt a file using a public SSH key

## Generate the symmetric key (32 bytes gives us the 256 bit key):
$ openssl rand -out secret.key 32
## Encrypt the file you’re sending, using the generated symmetric key:
$ openssl aes-256-cbc -in secretfile.txt -out secretfile.txt.enc -pass file:secret.key
## Encrypt the symmetric key, using the recipient’s public SSH key:
$ openssl rsautl -encrypt -oaep -pubin -inkey <(ssh-keygen -e -f recipients-key.pub -m PKCS8) -in secret.key -out secret.key.enc
## Delete the unencrypted symmetric key, so you don’t leave it around:
$ rm secret.key

Decrypt a file encrypted with a public SSH key

## First decrypt the symmetric.key:
$ openssl rsautl -decrypt -oaep -inkey ~/.ssh/id_rsa -in secret.key.enc -out secret.key
## Now the secret file can be decrypted, using the symmetric key:
$ openssl aes-256-cbc -d -in secretfile.txt.enc -out secretfile.txt -pass file:secret.key

Troubleshooting

x509: certificate signed by unknown authority

See OpenSSL:X509#certificate signed by unknown authority.

error:0A000126:SSL routines::unexpected eof while reading

It seems to be an OpenSSL issue on Ubuntu 22.04.

sudo apt update
sudo apt upgrade -y

-_- ;; Huh?

List of Block cipher

Block cipher

Algorithms

3-Way, AES, Akelarre, Anubis, ARIA, Blowfish, Camellia, CAST-128, CAST-256, CMEA, CS-Cipher, DEAL, DES, DES-X, FEAL, FOX, FROG, G-DES, GOST, ICE, IDEA, Iraqi block cipher, KASUMI, KHAZAD, Khufu and Khafre, LOKI89/91, LOKI97, Lucifer, MacGuffin, Madryga, MAGENTA, MARS, MISTY1, MMB, NewDES, Noekeon, RC2, RC5, RC6, REDOC, Red Pike, S-1, SAFER, SEED, Serpent, SHACAL, SHARK, Skipjack, Square, TEA, 3DES, Twofish, XTEA

Design

Feistel cipher, Key schedule, Product cipher, S-box, SPN

Cryptanalysis

Brute-force attack, Linear cryptanalysis / Differential cryptanalysis, Mod n, Related key, XSL

Standards

AES process, CRYPTREC NESSIE

Other

Avalanche effect, Block size, Initialization vector (IV), Key size, Mode of operation, Piling-up lemma, Weak key

See also

Favorite site

License issue

OpenSSL C Programming

Guide

References


  1. IT_story_web_-_what_is_ssl.zip ↩

  2. Symmetric-key encryption (5) - AES, 3DES ↩

  3. Jopenbusiness-OpenSSL.pdf ↩

  4. Opentutorials-HTTPS_and_SSL.pdf ↩

  5. Apache_-create_CSR_and_apply_ssl-_HanbiroSSL.pdf ↩

  6. Linux_personal_signature_generation_SSL_certificates_-_Zetawiki.pdf ↩

  7. Generating_keys_and_certificate_signing_requests_-Web_Fundamentals-_Google_Developers.pdf ↩

  8. Solanara-OpenSSL.pdf ↩

author Zer0 sitemap