1. Cryptography

Cryptography is used to protect information and communications.

This is typically done by using cryptographic techniques to scramble plaintext (ordinary text) into ciphertext (encoded text) and back again.

  • This scrambling process is called encryption.

  • The reverse process is called decryption.

Cryptography is concerned with the following objectives:

  • Confidentiality: The information can be understood by only the intended audience.

  • Integrity: The information cannot be altered in storage or in transit.

  • Non-repudiation: The creator of information cannot later deny that creation.

  • Authentication: The sender and receiver can confirm each other’s identity.

The encryption process requires an algorithm and a key.

  • The algorithm defines how data is transformed from plaintext into ciphertext and back to plaintext.

  • A key is a random string of data used as input to the algorithm.

All of the security of the process is contained in the key. Therefore, the key must be stored securely. The details of the most popular algorithms, however, are publicly available.

There are two types of encryption.

  • Symmetric encryption uses the same key for both encryption and decryption.

  • Asymmetric encryption uses different but mathematically related keys to perform encryption and decryption.

In cryptography, a cryptosystem is a suite of cryptographic algorithms needed to implement a particular security service, most commonly for achieving confidentiality (encryption).

Typically, a cryptosystem consists of three algorithms: one for key generation, one for encryption, and one for decryption.

The term cipher (sometimes cypher) is often used to refer to a pair of algorithms, one for encryption and one for decryption. Therefore, the term cryptosystem is most often used when the key generation algorithm is important. For this reason, the term cryptosystem is commonly used to refer to public key techniques; however both "cipher" and "cryptosystem" are used for symmetric key techniques.

1.1. Symmetric Encryption

Symmetric encryption uses the same key to encrypt plaintext into ciphertext and decrypt ciphertext back into plaintext. The necessary length of the key, expressed in number of bits, is determined by the algorithm. After the key is used to encrypt plaintext, the encrypted message is sent to the recipient who then decrypts the ciphertext.

symmetric keys

Symmetric-key algorithms are algorithms for cryptography that use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext.

  • The keys may be identical or there may be a simple transformation to go between the two keys.

  • The keys, in practice, represent a shared secret between two or more parties that can be used to maintain a private information link.

    This requirement that both parties have access to the secret key is one of the main drawbacks of symmetric key encryption, in comparison to public-key encryption (also known as asymmetric key encryption).

1.2. Asymmetric Encryption

If only symmetric encryption is used, the problem is that all parties to the communication must possess the private key. However, it is possible that unauthorized third parties can capture the key during transmission to authorized users. To address this issue, use asymmetric or public key cryptography instead.

In asymmetric cryptography, every user has two mathematically related keys called a key pair. One key is public and the other key is private. The key pair ensures that only the recipient has access to the private key needed to decrypt the data. The following illustration summarizes the asymmetric encryption process.

asymmetric keys
1 The recipient creates a public-private key pair and sends the public key to a CA.

The CA packages the public key in an X.509 certificate.

2 The sending party obtains the recipient’s public key from the CA.
3 The sender encrypts plaintext data using an encryption algorithm.

The recipient’s public key is used to perform encryption.

4 The sender transmits the ciphertext to the recipient.

It isn’t necessary to send the key because the recipient already has the private key needed to decrypt the ciphertext.

5 The recipient decrypts the ciphertext by using the specified asymmetric algorithm and the private key.

Public-key cryptography, or asymmetric cryptography, is a cryptographic system that uses public-private key pair of keys:

  • public keys which may be disseminated widely,

  • and private keys which are known only to the owner.

The generation of such keys depends on cryptographic algorithms based on mathematical problems to produce one-way functions. Effective security only requires keeping the private key private; the public key can be openly distributed without compromising security.

In such a system, any person can encrypt a message using the receiver’s public key, but that encrypted message can only be decrypted with the receiver’s private key.

1.2.1. Asymmetric Signing

Asymmetric algorithms can be used to protect data from modification (integrity) and prove the identity of the data creator (non-repudiation). The following illustration shows how asymmetric signing helps prove the sender’s identity.

asymmetric signing
1 The sender passes plaintext data through an asymmetric encryption algorithm, using the private key for encryption.

Notice that this scenario reverses use of the private and public keys outlined in the preceding section that detailed asymmetric encryption.

2 The resulting ciphertext is sent to the recipient.
3 The recipient obtains the originator’s public key from a directory.
4 The recipient decrypts the ciphertext by using the originator’s public key.

The resulting plaintext proves the originator’s identity because only the originator has access to the private key that initially encrypted the original text.

1.2.2. RSA (Rivest-Shamir-Adleman)

RSA (Rivest—​Shamir—​Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission.

In such a cryptosystem, the encryption key is public and it is different from the decryption key which is kept secret (private).

The acronym RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly described the algorithm in 1978.

RSA is a relatively slow algorithm, and because of this, it is less commonly used to directly encrypt user data.

More often, RSA passes encrypted shared keys for symmetric key cryptography which in turn can perform bulk encryption-decryption operations at much higher speed.

1.3. Combining Symmetric and Asymmetric Encryption

Symmetric and asymmetric encryption can be combined to take advantage of their relative strengths.

Symmetric encryption is much faster than asymmetric but, because of the necessity of sending private keys to other parties, is not as secure.

To combine the two types together,

  • symmetric encryption can be used to convert plaintext to ciphertext.

  • Asymmetric encryption is used to exchange the symmetric key.

This is demonstrated by the following diagram.

symmetric asymmetric encryption
1 The sender retrieves the recipient’s public key.
2 The sender generates a symmetric key and uses it to encrypt the original data.
3 The sender uses the recipient’s public key to encrypt the symmetric key.
4 The sender transmits the encrypted symmetric key and the ciphertext to the intended recipient.
5 The recipient uses the private key that matches the recipient’s public key to decrypt the sender’s symmetric key.
6 The recipient uses the symmetric key to decrypt the ciphertext.

1.4. Signing

Digital signing can be used to determine whether the data has been modified in transit or at rest.

  • The data is passed through a hash algorithm, a one-way function that produces a mathematical result from the given message.

  • The result is called a hash value, message digest, digest, signature, or thumbprint.

  • A hash value cannot be reversed to obtain the original message.

Because a small change in the message results in a significant change in the thumbprint, the hash value can be used to determine whether a message has been altered.

The following illustration shows how asymmetric encryption and hash algorithms can be used to verify that a message has not been modified.

1 The sender creates a plaintext message.
2 The sender hashes the plaintext message to create a message digest.
3 The sender encrypts the digest using a private key.
4 The sender transmits the plaintext message and the encrypted digest to the intended recipient.
5 The recipient decrypts the digest by using the sender’s public key.
6 The recipient runs the same hash algorithm that the sender used over the message.
7 The recipient compares the resulting signature to the decrypted signature.

If the digests are the same, the message was not modified during transmission.

2. ASN.1, DER and PEM

2.1. Abstract Syntax Notation One (ASN.1)

Abstract Syntax Notation One (ASN.1) is a standard interface description language for defining data structures that can be serialized and deserialized in a cross-platform way.

It is broadly used in telecommunications and computer networking, and especially in cryptography.

The advantage is that the ASN.1 description of the data encoding is independent of a particular computer or programming language.

Because ASN.1 is both human-readable and machine-readable, an ASN.1 compiler can compile modules into libraries of code, codecs, that decode or encode the data structures.

2.2. X.690 BER CER DER

X.690 is an ITU-T standard specifying several ASN.1 encoding formats:

  • Basic Encoding Rules (BER)

  • Canonical Encoding Rules (CER)

  • Distinguished Encoding Rules (DER)

The Basic Encoding Rules were the original rules laid out by the ASN.1 standard for encoding abstract information into a concrete data stream.

The rules, collectively referred to as a transfer syntax in ASN.1 parlance, specify the exact octet sequences which are used to encode a given data item.

The syntax defines such elements as:

  • the representations for basic data types,

  • the structure of length information,

  • and the means for defining complex or compound types based on more primitive types.

The BER syntax, along with two subsets of BER (the CER and the DER), are defined by the ITU-T’s X.690 standards document, which is part of the ASN.1 document series.

2.3. Privacy-Enhanced Mail (PEM)

Privacy-Enhanced Mail (PEM) is a de facto file format for storing and sending cryptographic keys, certificates, and other data, based on a set of 1993 IETF standards defining "privacy-enhanced mail."

Many cryptography standards use ASN.1 to define their data structures, and Distinguished Encoding Rules (DER) to serialize those structures.

Because DER produces binary output, it can be challenging to transmit the resulting files through systems, like electronic mail, that only support ASCII.

The PEM format solves this problem by encoding the binary data using base64.

  • PEM also defines a one-line header, consisting of -----BEGIN, a label, and -----, and a one-line footer, consisting of -----END, a label, and -----.

  • The label determines the type of message encoded.


PEM data is commonly stored in files with a

  • ".pem" suffix, a ".cer"

  • or ".crt" suffix (for certificates),

  • or a ".key" suffix (for public or private keys).

The label inside a PEM file represents the type of the data more accurately than the file suffix, since many different types of data can be saved in a ".pem" file.

In particular PEM refers to the header and base64 wrapper for a binary format contained within, but does not specify any type or format for the binary data, so that a PEM file may contain "almost anything base64 encoded and wrapped with BEGIN and END lines".

A PEM file may contain multiple instances.

  • For instance, an operating system might provide a file containing a list of trusted CA certificates,

  • or a web server might be configured with a "chain" file containing an end-entity certificate plus a list of intermediate certificates.

3. Public Key Cryptography Standards (PKCS)

In cryptography, PKCS stands for "Public Key Cryptography Standards".

These are a group of public-key cryptography standards devised and published by RSA Security LLC, starting in the early 1990s.

The company published the standards to promote the use of the cryptography techniques to which they had patents, such as the RSA algorithm, the Schnorr signature algorithm and several others.

Though not industry standards (because the company retained control over them), some of the standards in recent years have begun to move into the "standards-track" processes of relevant standards organizations such as the IETF and the PKIX working-group.

Version Name Comments



RSA Cryptography Standard

See RFC 8017. Defines the mathematical properties and format of RSA public and private keys (ASN.1-encoded in clear-text), and the basic algorithms and encoding/padding schemes for performing RSA encryption, decryption, and producing and verifying signatures.



Cryptographic Message Syntax Standard

See RFC 2315. Used to sign and/or encrypt messages under a PKI. Used also for certificate dissemination (for instance as a response to a PKCS #10 message). Formed the basis for S/MIME, which is as of 2010 based on RFC 5652, an updated Cryptographic Message Syntax Standard (CMS). Often used for single sign-on.



Private-Key Information Syntax Standard

See RFC 5958. Used to carry private certificate keypairs (encrypted or unencrypted).

PKCS #10


Certification Request Standard

See RFC 2986. Format of messages sent to a certification authority to request certification of a public key. See certificate signing request.

PKCS #12


Personal Information Exchange Syntax Standard

See RFC 7292. Defines a file format commonly used to store private keys with accompanying public key certificates, protected with a password-based symmetric key. PFX is a predecessor to PKCS #12. + This container format can contain multiple embedded objects, such as multiple certificates. Usually protected/encrypted with a password.

3.1. PKCS #1

In cryptography, PKCS #1 is the first of a family of standards called Public-Key Cryptography Standards (PKCS), published by RSA Laboratories.

  • It provides the basic definitions of and recommendations for implementing the RSA algorithm for public-key cryptography.

  • It defines

    • the mathematical properties of public and private keys,

    • primitive operations for encryption and signatures,

    • secure cryptographic schemes,

    • and related ASN.1 syntax representations.

$ openssl genrsa -out pkc1.pem 512
Generating RSA private key, 512 bit long modulus (2 primes)
e is 65537 (0x010001)

$ cat pkc1.pem

$ openssl pkcs8 -in rsa.pem -topk8 -nocrypt

3.2. PKCS #7

In cryptography, "PKCS #7: Cryptographic Message Syntax" (a.k.a. "CMS") is a standard syntax for storing signed and/or encrypted data.

  • PKCS #7 files may be stored both as raw DER format or as PEM format.

  • PEM format is the same as DER format but wrapped inside Base64 encoding and sandwiched in between ----BEGIN PKCS7---- and ----END PKCS7----.

  • Windows uses the ".p7b" file name extension for both these encodings.

A typical use of a PKCS #7 file would be to store certificates and/or certificate revocation lists.

Here’s an example of how to first download a certificate, then wrap it inside a PKCS #7 archive and then read from that archive:

$ openssl s_client -connect local.io:443 -xcertform PEM </dev/null 2>/dev/null  | openssl x509 > local.io.pem

$ openssl crl2pkcs7 -nocrl -certfile local.io.pem -out local.io.p7b

$ openssl pkcs7 -in local.io.p7b -noout -print_certs
subject=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = *.local.io

issuer=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = *.local.io

3.3. PKCS #8

In cryptography, PKCS #8 is a standard syntax for storing private key information.

The PKCS #8 private key may be encrypted with a passphrase using the PKCS #5 standards, which supports multiple ciphers.

PKCS #8 private keys are typically exchanged in the PEM base64-encoded format, for example:

$ openssl genpkey -algorithm RSA \
    -pkeyopt rsa_keygen_bits:512 -out key.pem   # 512 bits is a weak key, please specify 2048+ bits.

$ cat key.pem

$ openssl pkey -in key.pem -pubout
-----END PUBLIC KEY-----

$ openssl pkcs8 -in key.pem -topk8
Enter Encryption Password:
Verifying - Enter Encryption Password:

3.4. PKCS #10

In public key infrastructure (PKI) systems, a certificate signing request (also CSR or certification request) is a message sent from an applicant to a {certificate_authority}[certificate authority] in order to apply for a digital identity certificate.

It usually contains the public key for which the certificate should be issued, identifying information (such as a domain name) and integrity protection (e.g., a digital signature).

The most common format for CSRs is the PKCS #10 specification and another is the Signed Public Key and Challenge SPKAC format generated by some web browsers.

Before creating a CSR, the applicant first generates a key pair, keeping the private key secret.

The CSR contains information identifying the applicant (such as a distinguished name in the case of an X.509 certificate) which must be signed using the applicant’s private key.

The CSR also contains the public key chosen by the applicant.

The CSR may be accompanied by other credentials or proofs of identity required by the certificate authority, and the certificate authority may contact the applicant for further information.

A certification request consists of three main parts:

  • the certification request information,

  • a signature algorithm identifier,

  • and a digital signature on the certification request information.

The first part contains the significant information, including the public key.

The signature by the requester prevents an entity from requesting a bogus certificate of someone else’s public key. Thus the private key is needed to produce, but it is not part of, the CSR.

The PKCS#10 standard defines a binary format (DER) for encoding CSRs expressed in ASN.1.

A CSR may also be represented as a Base64 encoded PKCS#10 (PEM).

$ openssl genrsa -out key.pem 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
e is 65537 (0x010001)

$ openssl req -x509 -new -key key.pem -subj "/CN=example.com" -out req.pem

$ cat req.pem

$ openssl asn1parse -i -in req.pem
    0:d=0  hl=4 l= 781 cons: SEQUENCE
    4:d=1  hl=4 l= 501 cons:  SEQUENCE
    8:d=2  hl=2 l=   3 cons:   cont [ 0 ]
   10:d=3  hl=2 l=   1 prim:    INTEGER           :02
   13:d=2  hl=2 l=  20 prim:   INTEGER           :43B48F19F35CA1A549E66FC8E87CA57B2EC81B68
   35:d=2  hl=2 l=  13 cons:   SEQUENCE
   37:d=3  hl=2 l=   9 prim:    OBJECT            :sha256WithRSAEncryption
   48:d=3  hl=2 l=   0 prim:    NULL
   50:d=2  hl=2 l=  22 cons:   SEQUENCE
   52:d=3  hl=2 l=  20 cons:    SET
   54:d=4  hl=2 l=  18 cons:     SEQUENCE
   56:d=5  hl=2 l=   3 prim:      OBJECT            :commonName
   61:d=5  hl=2 l=  11 prim:      UTF8STRING        :example.com

4. Public Key Certificates

In cryptography, a public key certificate, also known as a digital certificate or identity certificate, is an electronic document used to prove the ownership of a public key.

The certificate includes information about the key, information about the identity of its owner (called the subject), and the digital signature of an entity that has verified the certificate’s contents (called the issuer).

If the signature is valid, and the software examining the certificate trusts the issuer, then it can use that key to communicate securely with the certificate’s subject.

In email encryption, code signing, and e-signature systems, a certificate’s subject is typically a person or organization.

However, in Transport Layer Security (TLS) a certificate’s subject is typically a computer or other device, though TLS certificates may identify organizations or individuals in addition to their core role in identifying devices.

TLS, sometimes called by its older name Secure Sockets Layer (SSL), is notable for being a part of HTTPS, a protocol for securely browsing the web.

In a typical public-key infrastructure (PKI) scheme, the certificate issuer is a certificate authority (CA), usually a company that charges customers to issue certificates for them. By contrast, in a web of trust scheme, individuals sign each other’s keys directly, in a format that performs a similar function to a public key certificate.

The most common format for public key certificates is defined by X.509.

Because X.509 is very general, the format is further constrained by profiles defined for certain use cases, such as Public Key Infrastructure (X.509) as defined in RFC 5280.

5. X.509 Public Key Certificates

In cryptography, X.509 is a standard defining the format of public key certificates.

X.509 certificates are used in many Internet protocols, including TLS/SSL, which is the basis for HTTPS, the secure protocol for browsing the web.

They are also used in offline applications, like electronic signatures.

X.509 certificates are digital documents that represent a user, computer, service, or device.

  • They are issued by a certification authority (CA), subordinate CA, or registration authority or self-signed and contain the public key of the certificate subject.

  • They do not contain the subject’s private key which must be stored securely.

Public key certificates are documented by RFC 5280. They are digitally signed and, in general, contain the following information:

  • Information about the certificate subject

  • The public key that corresponds to the subject’s private key

  • Information about the issuing CA

  • The supported encryption and/or digital signing algorithms

  • Information to determine the revocation and validity status of the certificate

When a certificate is signed by a trusted certificate authority, or validated by other means, someone holding that certificate can rely on the public key it contains to establish secure communications with another party, or validate documents digitally signed by the corresponding private key.

5.1. Certificate Fields

Over time there have been three certificate versions. Each version adds fields to the one before. Version 3 is current and contains version 1 and version 2 fields in addition to version 3 fields.

Version 1 defined the following fields:

  • Version: A value (1, 2, or 3) that identifies the version number of the certificate

  • Serial Number: A unique number for each certificate issued by a CA

  • CA Signature Algorithm: Name of the algorithm the CA uses to sign the certificate contents

  • Issuer Name: The distinguished name (DN) of the certificate’s issuing CA

  • Validity Period: The time period for which the certificate is considered valid

  • Subject Name: Name of the entity represented by the certificate

  • Subject Public Key Info: Public key owned by the certificate subject

Version 2 added the following fields containing information about the certificate issuer. These fields are, however, rarely used.

  • Issuer Unique ID: A unique identifier for the issuing CA as defined by the CA

  • Subject Unique ID: A unique identifier for the certificate subject as defined by the issuing CA

Version 3 certificates added the following extensions:

  • Authority Key Identifier: This can be one of two values:

    • The subject of the CA and serial number of the CA certificate that issued this certificate

    • A hash of the public key of the CA that issued this certificate

  • Subject Key Identifier: Hash of the current certificate’s public key

  • Key Usage Defines the service for which a certificate can be used.

    This can be one or more of the following values:

    • Digital Signature

    • Non-Repudiation

    • Key Encipherment

    • Data Encipherment

    • Key Agreement

    • Key Cert Sign

    • CRL Sign

    • Encipher Only

    • Decipher Only

  • Private Key Usage Period: Validity period for the private key portion of a key pair

  • Certificate Policies: Policies used to validate the certificate subject

  • Policy Mappings: Maps a policy in one organization to policy in another

  • Subject Alternative Name: List of alternate names for the subject

  • Issuer Alternative Name: List of alternate names for the issuing CA

  • Subject Dir Attribute: Attributes from an X.500 or LDAP directory

  • Basic Constraints: Allows the certificate to designate whether it is issued to a CA, or to a user, computer, device, or service.

    This extension also includes a path length constraint that limits the number of subordinate CAs that can exist.

  • Name Constraints: Designates which namespaces are allowed in a CA-issued certificate

  • Policy Constraints: Can be used to prohibit policy mappings between CAs

  • Extended Key Usage: Indicates how a certificate’s public key can be used beyond the purposes identified in the Key Usage extension

  • CRL Distribution Points: Contains one or more URLs where the base certificate revocation list (CRL) is published

  • Inhibit anyPolicy: Inhibits the use of the All Issuance Policies OID ( in subordinate CA certificates

  • Freshest CRL: Contains one or more URLs where the issuing CA’s delta CRL is published

  • Authority Information Access: Contains one or more URLs where the issuing CA certificate is published

  • Subject Information Access: Contains information about how to retrieve additional details for a certificate subject

5.2. Certificate Formats

There are several commonly used filename extensions for X.509 certificates.

  • .pem – (Privacy-enhanced Electronic Mail) Base64 encoded DER certificate, enclosed between "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"

  • .cer, .crt, .der – usually in binary DER form, but Base64-encoded certificates are common too

  • .p7b, .p7cPKCS#7 SignedData structure without data, just certificate(s) or CRL(s)

  • .p12PKCS#12, may contain certificate(s) (public) and private keys (password protected)

  • .pfx – PFX, predecessor of PKCS#12 (usually contains data in PKCS#12 format, e.g., with PFX files generated in IIS)

PKCS#7 is a standard for signing or encrypting (officially called "enveloping") data. Since the certificate is needed to verify signed data, it is possible to include them in the SignedData structure. A .P7C file is a degenerated SignedData structure, without any data to sign.

PKCS#12 evolved from the personal information exchange (PFX) standard and is used to exchange public and private objects in a single file.

6. OpenSSL

OpenSSL is a software library for applications that secure communications over computer networks against eavesdropping or need to identify the party at the other end. It is widely used in Internet web servers, serving a majority of all web sites.

OpenSSL contains an open-source implementation of the SSL and TLS protocols. The core library, written in the C programming language, implements basic cryptographic functions and provides various utility functions. Wrappers allowing the use of the OpenSSL library in a variety of computer languages are available.

The OpenSSL Software Foundation (OSF) represents the OpenSSL project in most legal capacities including contributor license agreements, managing donations, and so on. OpenSSL Software Services (OSS) also represents the OpenSSL project, for Support Contracts.

Versions are available for most Unix and Unix-like operating systems (including Solaris, Linux, macOS, QNX, and the various open-source BSD operating systems), OpenVMS and Microsoft Windows.

OPENSSL(1SSL)                                                                 OpenSSL                                                                 OPENSSL(1SSL)

       openssl - OpenSSL command line tool

       openssl command [ command_opts ] [ command_args ]

       openssl list [ standard-commands | digest-commands | cipher-commands | cipher-algorithms | digest-algorithms | public-key-algorithms]

       openssl no-XXX [ arbitrary options ]

       OpenSSL is a cryptography toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) network protocols and related
       cryptography standards required by them.

       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

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

       The openssl program provides a rich variety of commands (command in the SYNOPSIS above), each of which often has a wealth of options and arguments
       (command_opts and command_args in the SYNOPSIS).

       Detailed documentation and use cases for most standard subcommands are available (e.g., x509(1) or openssl-x509(1)).

   Standard Commands
           Parse an ASN.1 sequence.

           Generation of Private Key or Parameters.

           PKCS#12 Data Management.

           PKCS#7 Data Management.

           PKCS#8 format private key conversion tool.

           Public and private key management.

           Public key algorithm cryptographic operation utility.

           PKCS#10 X.509 Certificate Signing Request (CSR) Management.

           This implements a generic SSL/TLS client which can establish a transparent connection to a remote server speaking SSL/TLS. It's intended for testing
           purposes only and provides only rudimentary interface functionality but internally uses mostly all functionality of the OpenSSL ssl library.

           X.509 Certificate Data Management.

6.1. Self-signed Certificate

  • Generate a self signed root certificate

    openssl req -x509 \
        -nodes \
        -newkey rsa:2048 -keyout key.pem \
        -days 30 \
        -out cert.pem \
        -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=example.com" \
        -addext "subjectAltName=DNS:example.com,DNS:*.example.com"
  • Generate a self signed root certificate from a private key

    # Generate a 2048 bit RSA key (same as: openssl genrsa -out key.pem 2048)
    openssl genpkey \
        -algorithm RSA \
        -pkeyopt rsa_keygen_bits:2048 \
        -out key.pem
    # Generate a certificate request from a private key
    openssl req -x509 \
        -new \
        -key key.pem \
        -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=example.com" \
        -addext "subjectAltName=DNS:example.com,DNS:*.example.com" \
        -out cert.pem
    # Display the subject and fingerprint of the cert cert.pem
    openssl x509 -in cert.pem -subject -ext subjectAltName -fingerprint -noout 2>/dev/null
    subject=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com
    X509v3 Subject Alternative Name:
        DNS:example.com, DNS:*.example.com
    SHA1 Fingerprint=43:FA:67:3F:45:95:93:5D:25:BE:15:2E:F1:C4:98:1D:8F:52:77:07
    # Calculate the fingerprint/thumbprint with .der format
    $ openssl x509 -in baidu.pem -outform der | sha1sum
    43fa673f4595935d25be152ef1c4981d8f527707  -

6.2. Show Certificate:

$ openssl x509 -in cert.pem -noout -issuer
issuer=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com

$ openssl x509 -in cert.pem -noout -subject
subject=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com

$ openssl x509 -in cert.pem -noout -fingerprint
SHA1 Fingerprint=1A:EB:13:40:38:AD:2E:42:57:A6:8A:BB:09:7A:5B:70:8B:69:C6:20

$ openssl x509 -in cert.pem -noout -dates
notBefore=Nov  9 06:46:15 2021 GMT
notAfter=Dec  9 06:46:15 2021 GMT

$ openssl x509 -in cert.pem -noout -text
        Version: 3 (0x2)
        Serial Number:
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com
            Not Before: Dec 21 07:49:22 2021 GMT
            Not After : Jan 20 07:49:22 2022 GMT
        Subject: C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
            X509v3 Authority Key Identifier:

            X509v3 Basic Constraints: critical
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:*.example.com
    Signature Algorithm: sha256WithRSAEncryption

6.3. Sign Certificate Signing Request

  • Generate a self signed root certificate

    openssl req \
        -x509 \
        -nodes \
        -newkey rsa:2048 -keyout ca.key \
        -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=example.com" \
        -out ca.crt
  • Generate a certificate signing request

    openssl req -nodes \
        -newkey rsa:2048 -keyout localhost.key \
        -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=localhost" \
        -out localhost.csr
  • Display the contents of the certificate request

    openssl req -in localhost.csr -noout -text
    Certificate Request:
            Version: 1 (0x0)
            Subject: C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = localhost
            Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                    RSA Public-Key: (2048 bit)
                    Exponent: 65537 (0x10001)
        Signature Algorithm: sha256WithRSAEncryption
  • Sign a certificate request using the CA certificate above

    openssl x509 \
        -req \
        -in localhost.csr \
        -CA ca.crt \
        -CAkey ca.key \
        -CAcreateserial \
        -days 10000 \
        -out localhost.crt
  • Display the contents of the certificate

    $ openssl x509 -in localhost.crt -subject -issuer -noout
    subject=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = localhost
    issuer=C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = example.com

6.4. Verify Certificate Signature

$ openssl req -x509 \
    -nodes \
    -newkey rsa:2048 -keyout key.pem \
    -days 30 \
    -out cert.pem \
    -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=example.com" \
    -addext "subjectAltName=DNS:example.com,DNS:*.example.com"
Generating a RSA private key
writing new private key to 'key.pem'

$ openssl x509 \
    -in cert.pem \
    -text \
    -noout \
    -certopt ca_default \
    -certopt no_validity \
    -certopt no_serial \
    -certopt no_subject \
    -certopt no_extensions \
    -certopt no_signame | \
    grep -v 'Signature Algorithm' | \
    tr -d '[:space:]:' | \
    xxd -r -p > cert-encrypt-sig.bin

$ od -x -A n --endian=big cert-encrypt-sig.bin
 af04 bea5 565e d3af 0156 3796 289e 7860
 ba23 969f 7c85 b832 03fc ddb7 1b92 811c
 3e53 42ed 7405 aa1b af10 b5b9 2fdc c821
 1c47 1783 a78c 9765 7964 b064 9e29 e2f2
 9f53 ba98 a533 7589 c6a9 ccf3 d56f dbdb
 e796 99ba 0b5b 9f55 f6a1 407d 7d09 5117
 e5cc 54a2 1748 ef6b c140 1bce c63c 400d
 6faa f5e8 ea8e 2e16 163a 47df 7446 90c6
 4d41 8365 53c1 5d2e 8834 eb1e 185d 516d
 3b17 5b93 1d71 888e 1a0b 17c4 f861 baac
 af8b 441d 0105 08ba 9f1a a8ba 62a5 45f6
 56d8 9177 7bec 488b 58e0 f4f6 ec90 a2ce
 765b 210b b3bd fbc5 38c5 f884 a362 b4d9
 44d1 6718 a86b 6659 7fef 5a92 989f bba6
 1801 15fd b94a 0c8b c169 944c c68c e4f1
 af9b 6c11 bf58 9f8f 765d 0b35 9b81 0c39

$ openssl x509 -in cert.pem -noout -text
    Signature Algorithm: sha256WithRSAEncryption

$ openssl pkeyutl -decrypt \
    -inkey pkc1-key.pem -pkeyopt rsa_padding_mode:none \
    -in cert-sig-decrypted.bin \
    -out cert-decrypted.bin

$ openssl asn1parse -inform der -in cert-sig-decrypted.bin
    0:d=0  hl=2 l=  49 cons: SEQUENCE
    2:d=1  hl=2 l=  13 cons: SEQUENCE
    4:d=2  hl=2 l=   9 prim: OBJECT            :sha256
   15:d=2  hl=2 l=   0 prim: NULL
   17:d=1  hl=2 l=  32 prim: OCTET STRING      [HEX DUMP]:886B28CF2FF661E2972966C7E5CC175B393F7620C388B25BA027CE92696856DB

$ openssl asn1parse -inform der -in cert-sig-decrypted.bin \
    | grep 'HEX DUMP' \
    | cut -d ':' -f4 \
    | tr '[:upper:]' '[:lower:]'

$ openssl asn1parse -in cert.pem -strparse 4 -noout -out - \
    | openssl dgst -sha256 \
    | cut -d ' ' -f2

6.5. Generate Certificate with subjectAltName

openssl req -x509 \
  -nodes \
  -newkey rsa:4096 \
  -days 3650 \
  -keyout local.io.ca.key \
  -out local.io.ca.crt \
  -subj "/C=CN/ST=Shanghai/L=Shanghai/O=Global Security/OU=IT Department/CN=*.local.io" \
  -addext "subjectAltName=DNS:local.io,DNS:*.local.io"
$ openssl x509 -in local.io.ca.crt -noout -text
        Version: 3 (0x2)
. . .
        Subject: C = CN, ST = Shanghai, L = Shanghai, O = Global Security, OU = IT Department, CN = *.local.io
        X509v3 extensions:
            X509v3 Subject Key Identifier:
            X509v3 Authority Key Identifier:

            X509v3 Basic Constraints: critical
            X509v3 Subject Alternative Name:
                DNS:local.io, DNS:*.local.io
. . .

6.6. Create CSR with Config File

  • Generate a server.key with 2048bit

    openssl genrsa -out server.key 2048
  • Create a config file (e.g. csr.conf) for generating a CSR

    # csr.conf
    [ req ]
    default_bits = 2048
    prompt = no
    default_md = sha256
    req_extensions = req_ext
    distinguished_name = dn
    [ dn ]
    # C = <country>
    C = CN
    # ST = <state>
    ST = Shanghai
    # L = <city>
    L = Shanghai
    # O = <organization>
    # 1.O = <organization>
    # 2.O = <organization>
    O = IT Department
    # OU = <organization unit>
    # 1.OU = <organization unit>
    # 2.OU = <organization unit>
    OU = Developer
    # CN = <MASTER_IP>
    CN = developer
    [ req_ext ]
    subjectAltName = @alt_names
    [ alt_names ]
    DNS.1 = kubernetes
    DNS.2 = kubernetes.default
    DNS.3 = kubernetes.default.svc
    DNS.4 = kubernetes.default.svc.cluster
    DNS.5 = kubernetes.default.svc.cluster.local
    #IP.1 = <MASTER_IP>
    IP.1 =
    IP.2 =
    [ v3_ext ]
  • Generate the certificate signing request based on the config file

    openssl req -new -key server.key -out server.csr -config csr.conf
  • Generate the server certificate using the ca.key, ca.crt and server.csr

    openssl x509 \
        -req \
        -in server.csr \
        -CA ca.crt -CAkey ca.key \
        -CAcreateserial \
        -days 10000 \
        -extensions v3_ext \
        -extfile csr.conf \
        -out server.crt

6.7. How to Convert a Certificate into the Appropriate Format

If your server/device requires a different certificate format other than Base64 encoded X.509, a third party tool such as OpenSSL can be used to convert the certificates into the appropriate format.

The PEM format is the most common format used for certificates. Extensions used for PEM certificates are cer, crt, and pem. They are Base64 encoded ASCII files.

The DER format is the binary form of the certificate. DER formatted certificates do not contain the "BEGIN CERTIFICATE/END CERTIFICATE" statements. DER formatted certificates most often use the '.der' extension.

  • Convert x509 to PEM

    openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem
  • Convert PEM to DER

    openssl x509 -outform der -in certificatename.pem -out certificatename.der
  • Convert DER to PEM

    openssl x509 -inform der -in certificatename.der -out certificatename.pem
  • Convert pfx to PEM

    The PKCS#12 or PFX format is a binary format for storing the server certificate, intermediate certificates, and the private key in one encryptable file. PFX files usually have extensions such as .pfx and .p12. PFX files are typically used on Windows machines to import and export certificates and private keys.
    openssl pkcs12 -in certificatename.pfx -out certificatename.pem
  • Convert CER and Private Key to PFX

    openssl pkcs12 \
      -export \
      -in certificatename.cer \
      -inkey privateKey.key \
      -out certificatename.pfx # -certfile cacert.cer