Master OpenSSL: Comprehensive Guide to Encryption, Keys, and Certificates

This article provides a thorough walkthrough of OpenSSL, covering cryptographic standards, symmetric and public‑key encryption, message digests, digital certificate creation and management, plus practical command‑line examples for each operation, making it a valuable resource for security professionals and developers.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master OpenSSL: Comprehensive Guide to Encryption, Keys, and Certificates

疑今者察之古,不知来者视之往。

Navigation

Introduction

Symmetric Encryption

Public‑Key Encryption

Message Digests

Digital Certificates

Miscellaneous

Introduction

Cryptographic standards, like PKCS# and X.509, define how keys, certificates, and algorithms are formatted and used. OpenSSL is a command‑line toolkit that implements these standards, offering symmetric and asymmetric encryption, digest calculation, and certificate generation, signing, and verification.

Symmetric Encryption

Symmetric algorithms use the same secret key for encryption and decryption. You can list all supported ciphers with openssl list -cipher-commands. The enc sub‑command provides a convenient tool for symmetric encryption and decryption.

openssl enc command

Usage: enc [options]

General options:
 -help               Display this summary
 -list               List ciphers
 -ciphers            Alias for -list
 -e                  Encrypt
 -d                  Decrypt
 -p                  Print the iv/key
 -P                  Print the iv/key and exit
 -engine val         Use engine, possibly a hardware device

Input options:
 -in infile          Input file
 -k val              Passphrase
 -kfile infile       Read passphrase from file

Output options:
 -out outfile        Output file
 -pass val           Passphrase source
 -v                  Verbose output
 -a                  Base64 encode/decode
 -base64             Same as -a
 -A                  Use single‑line base64 output

Encryption options:
 -nopad              Disable standard block padding
 -salt               Use salt in the KDF (default)
 -nosalt             Do not use salt in the KDF
 -debug              Print debug info
 -bufsize val        Buffer size
 -K val              Raw key, in hex
 -S val              Salt, in hex
 -iv val             IV, in hex
 -md val             Digest to derive key from passphrase
 -iter +int          Iteration count for PBKDF2
 -pbkdf2             Use PBKDF2
 -none               Do not encrypt
 -*                  Any supported cipher

Random state options:
 -rand val           Load file(s) into RNG
 -writerand outfile  Write random data to file

Provider options:
 -provider-path val  Provider load path
 -provider val       Provider to load
 -propquery val      Property query for algorithms

Example 1: Encrypt a file with AES‑128‑CBC

// Encrypt test.txt with AES‑128‑CBC using passphrase "pass"
openssl enc -e -aes-128-cbc -in test.txt -k pass -out test-aes-enc.txt -v

// Decrypt the resulting file
openssl enc -d -aes-128-cbc -in test-aes-enc.txt -k pass -out test-aes-dec.txt -v

Example 2: Base64 encode a string

// Encode
echo -n "12345" | openssl enc -e -base64 -in -

// Decode
echo "MTIzNDU=" | openssl enc -d -base64 -in -

Example 3: Encrypt a file and output Base64

// Encrypt and Base64‑encode
openssl enc -aes-256-cbc -a -salt -in file.txt -out file.enc

// Decrypt the Base64‑encoded ciphertext
openssl enc -d -aes-256-cbc -a -in file.enc

Public‑Key Encryption

Public‑key algorithms use a key pair: the public key encrypts (or verifies signatures) and the private key decrypts (or signs). OpenSSL supports RSA, DSA, DH, and EC. The most common operations involve RSA, accessed via the genrsa, rsa, and rsautl sub‑commands.

Generating an RSA private key (genrsa)

Usage: genrsa [options] numbits

General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device

Output options:
 -out outfile        Output the key to file
 -passout val        Pass phrase for output key
 -primes +int       Number of primes
 -verbose            Verbose output
 -traditional        Use traditional PEM format
 -*                  Encrypt the output with any supported cipher

Random state options:
 -rand val           Load file(s) into RNG
 -writerand outfile  Write random data to file

Provider options:
 -provider-path val  Provider load path
 -provider val       Provider to load
 -propquery val      Property query for algorithms

Parameters:
 numbits             Size of key in bits

Example: Create an unencrypted 1024‑bit RSA key

openssl genrsa -out private.pem 1024 -verbose

Example: Create a password‑protected RSA key (AES‑128‑CBC)

openssl genrsa -aes-128-cbc -out pri.pem -verbose

Managing RSA keys (rsa)

Usage: rsa [options]

General options:
 -help               Display this summary
 -check              Verify key consistency
 -*                  Any supported cipher
 -engine val         Use engine, possibly a hardware device

Input options:
 -in val             Input file
 -inform format      Input format (DER/PEM/P12/ENGINE)
 -pubin              Expect a public key in input file
 -RSAPublicKey_in    Input is an RSAPublicKey
 -passin val         Pass phrase source for input key

Output options:
 -out outfile        Output file
 -outform format     Output format (DER PEM PVK)
 -pubout             Output a public key
 -RSAPublicKey_out   Output as RSAPublicKey
 -passout val        Pass phrase source for output key
 -noout              Do not print key
 -text               Print key in text form
 -modulus            Print RSA key modulus
 -traditional        Use traditional format for private keys

PVK options:
 -pvk-strong         Enable "Strong" PVK encoding
 -pvk-weak           Enable "Weak" PVK encoding
 -pvk-none           Do not enforce PVK encoding

Provider options:
 -provider-path val  Provider load path
 -provider val       Provider to load
 -propquery val      Property query for algorithms

Example: View private key details

openssl rsa -in priv.pem -text

Example: Add, remove, or change password protection

// Add password protection
openssl rsa -in RSA.pem -des3 -passout pass:123456 -out E_RSA.pem

// Remove password protection
openssl rsa -in E_RSA.pem -passin pass:123456 -out P_RSA.pem

// Change encryption algorithm to aes128
openssl rsa -in RSA.pem -passin pass:123456 -aes128 -passout pass:123456 -out E_RSA.pem

Example: Convert key format (PEM to DER)

openssl rsa -in RSA.pem -passin pass:123456 -des -passout pass:123456 -outform der -out rsa.der

Extract public key from a private key

openssl rsa -in private.pem -pubout -out public.pem

RSA encryption/decryption and signing (rsautl)

Usage: rsautl [options]

General options:
 -help                Display this summary
 -sign                Sign with private key
 -verify              Verify with public key
 -encrypt             Encrypt with public key
 -decrypt             Decrypt with private key
 -engine val          Use engine, possibly a hardware device

Input options:
 -in infile           Input file
 -inkey val           Input key
 -keyform PEM|DER|ENGINE  Private key format
 -pubin               Input is an RSA public key
 -certin              Input is a cert carrying an RSA public key
 -rev                 Reverse order of input buffer
 -passin val          Pass phrase source for input key

Output options:
 -out outfile         Output file
 -raw                 Use no padding
 -pkcs                Use PKCS#1 v1.5 padding (default)
 -x931                Use ANSI X9.31 padding
 -oaep                Use PKCS#1 OAEP padding
 -asn1parse           Run output through asn1parse
 -hexdump             Hex dump output

Random state options:
 -rand val            Load file(s) into RNG
 -writerand outfile   Write random data to file

Provider options:
 -provider-path val   Provider load path
 -provider val        Provider to load
 -propquery val       Property query for algorithms

Example: Encrypt and decrypt a file with RSA keys

// Encrypt with public key
openssl rsautl -encrypt -in plain.text -inkey public.pem -out encrypt.text

// Decrypt with private key
openssl rsautl -decrypt -in encrypt.text -inkey private.pem -out replain.text

Example: Sign and verify a file

// Sign with private key
openssl rsautl -sign -in plain.text -inkey private.pem -out signed.text

// Verify with public key
openssl rsautl -verify -in signed.text -pubin -inkey public.pem -out verify.text

Message Digests

Digest algorithms produce a fixed‑length hash from arbitrary data, useful for integrity verification. List supported digests with openssl list -digest-commands. The dgst sub‑command performs hashing, signing, and verification.

openssl dgst command

Usage: dgst [options] [file...]

General options:
 -help               Display this summary
 -list               List digests
 -engine val         Use engine, possibly a hardware device
 -engine_impl        Also use engine for digest operations
 -passin val         Pass phrase source for input key

Output options:
 -c                  Print digest with colons
 -r                  Print digest in coreutils format
 -out outfile        Output to file instead of stdout
 -keyform format     Key file format (ENGINE ignored)
 -hex                Print as hex dump
 -binary             Print in binary form
 -xoflen +int        Output length for XOF algorithms
 -d                  Print debug info
 -debug              Print debug info

Signing options:
 -sign val           Sign digest using private key
 -verify val         Verify a signature using public key
 -prverify val       Verify a signature using private key
 -sigopt val         Signature parameter n:v
 -signature infile   File with signature to verify
 -hmac val           Create HMAC with key
 -mac val            Create MAC (not necessarily HMAC)
 -macopt val         MAC algorithm parameters n:v or key
 -fips-fingerprint  Compute HMAC with FIPS fingerprint key

Random state options:
 -rand val           Load file(s) into RNG
 -writerand outfile  Write random data to file

Provider options:
 -provider-path val  Provider load path
 -provider val       Provider to load
 -propquery val      Property query for algorithms

Parameters:
 file                Files to digest (default stdin)

Example: Compute MD5 of a file

openssl dgst -md5 test.txt

Example: Sign and verify a file

// Sign with private key
openssl dgst -sign private.pem -out test.text plain.text

// Verify with public key
openssl dgst -verify public.pem -signature test.text plain.text

Digital Certificates

Certificates bind a public key to an identity, signed by a trusted authority (CA). OpenSSL can generate certificate requests, self‑signed certificates, and manage existing certificates.

Generating and handling certificate requests (req)

Usage: req [options]

General options:
 -help                 Display this summary
 -engine val           Use engine, possibly a hardware device
 -keygen_engine val    Engine for key generation
 -in infile            X.509 request input file (default stdin)
 -inform PEM|DER       Input format
 -verify               Verify self‑signature on the request

Certificate options:
 -new                  New request
 -config infile        Request template file
 -section val          Config section to use (default "req")
 -utf8                 Input characters are UTF‑8 (default ASCII)
 -nameopt val          Name printing options
 -reqopt val           Request text options
 -text                 Text form of request
 -x509                 Output an X.509 certificate instead of a request
 -CA infile            Issuer certificate for signing
 -CAkey val            Issuer private key
 -subj val             Set or modify subject of request or certificate
 -days +int            Number of days certificate is valid
 -set_serial val       Serial number to use
 -addext val           Additional certificate extension (key=value)
 -extensions val       Certificate extension section
 -reqexts val          Request extension section
 -precert              Add poison extension (implies -new)

Key and signing options:
 -key val              Key for signing
 -keyform format       Key file format
 -pubkey               Output public key
 -keyout outfile       Write private key to file
 -passin val           Pass phrase source for private key
 -passout val          Pass phrase source for output key
 -newkey val           Generate new key (alg:bits or file)
 -pkeyopt val          Public key options n:v
 -sigopt val           Signature parameter n:v
 -vfyopt val           Verification parameter n:v
 -*                    Any supported digest

Output options:
 -out outfile          Output file (default stdout)
 -outform PEM|DER      Output format
 -batch                Do not ask any questions
 -verbose              Verbose output
 -noenc                Do not encrypt private keys
 -nodes                Do not encrypt private keys (deprecated)
 -noout                Do not output the request
 -newhdr               Output "NEW" in header lines
 -modulus              RSA modulus

Random state options:
 -rand val             Load file(s) into RNG
 -writerand outfile    Write random data to file

Provider options:
 -provider-path val    Provider load path
 -provider val         Provider to load
 -propquery val        Property query for algorithms

Example: Create a certificate request

// Use an existing private key
openssl req -new -key private.pem -out request.csr

// Generate a new key and request automatically
openssl req -new -out request.csr

// Generate a 1024‑bit RSA key without encryption and a CSR
openssl req -new -newkey rsa:1024 -nodes -out client.csr -keyout RSA.pem -subj /C=AU/ST=Some-State/O=Internet

// Generate a CSR without interactive prompts
openssl req -new -nodes -out request.csr -batch

Example: View a CSR

openssl req -in request.csr -text

Example: Extract public key from a CSR

openssl req -in client.csr -pubkey -noout > pub.pem

Example: Create a self‑signed root CA certificate

// Generate a private key for the CA
openssl genrsa -out ca.pem 2048

// Create a self‑signed root certificate valid for 365 days
openssl req -new -x509 -days 365 -key ca.pem -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=Acme Root CA" -out ca.cer

Example: Sign a CSR with the root CA

// Generate a server CSR
openssl req -newkey rsa:2048 -nodes -keyout server.pem -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=localhost" -out server.csr

// Sign the CSR with the CA to produce a certificate
openssl x509 -sha256 -req -days 365 -in server.csr -CA ca.cer -CAkey ca.pem -CAcreateserial -out server.cer

Miscellaneous

Generate random bytes (rand)

// Generate 3 random bytes in hexadecimal
openssl rand -hex 3

Generate password hashes (passwd)

// Simple hash of a password
openssl passwd 12345

// Hash with a specific salt
openssl passwd -salt 'z' 12345

Verify a certificate (verify)

openssl verify cert.pem

Run a TLS server and client (s_server, s_client)

// Start a TLS server on port 4433
openssl s_server -cert mycert.pem -www -accept 4433

// Connect to a TLS server
openssl s_client -connect remote.host:4433

Source: https://www.cnblogs.com/kqdssheng/p/17945857

(© Original author, all rights reserved)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

command-lineencryptionOpenSSLdigital certificates
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.