What it is
OpenSSL is a robust, widely-used toolkit for TLS/SSL and general-purpose cryptography, enabling secure communication and data manipulation. You reach for it for generating keys, certificates, encrypting/decrypting files, and performing various cryptographic operations.
Installation
Linux (Debian/Ubuntu)
sudo apt update
sudo apt install openssl
Linux (Fedora/CentOS/RHEL)
sudo dnf install openssl
# or
sudo yum install openssl
macOS
OpenSSL is often pre-installed, but you can install or update it via Homebrew:
brew update
brew install openssl
Note: macOS might use its own libssl or security framework. To ensure you’re using the Homebrew version, you might need to adjust your PATH or explicitly call the binary (e.g., /usr/local/opt/openssl/bin/openssl).
Windows
Download the pre-compiled binaries from the official OpenSSL website (https://www.openssl.org/community/binaries.html) or use a package manager like Chocolatey:
choco install openssl
After installation, ensure the OpenSSL bin directory is added to your system’s PATH environment variable.
Core Concepts
- Keys: Digital representations of cryptographic secrets.
- Private Key: Secret key, must be kept confidential. Used to decrypt data encrypted with the corresponding public key and to sign data.
- Public Key: Can be shared freely. Used to encrypt data that only the corresponding private key can decrypt, and to verify signatures made with the corresponding private key.
- Certificates (X.509): Digital documents that bind a public key to an identity (e.g., a domain name, an organization). They are signed by a Certificate Authority (CA) to vouch for their authenticity.
- CSR (Certificate Signing Request): A message sent to a CA when applying for a digital certificate. It contains the public key and identity information.
- Symmetric Encryption: Uses a single key for both encryption and decryption (e.g., AES). Faster for large amounts of data.
- Asymmetric Encryption: Uses a pair of keys (public/private). Slower but essential for key exchange and digital signatures.
- Hashes: One-way cryptographic functions that produce a fixed-size "fingerprint" of data (e.g., SHA-256). Used for integrity checks.
Commands / Usage
Key Generation
Generate an RSA Private Key
openssl genrsa -out private.key 2048
Generates a 2048-bit RSA private key and saves it to private.key.
Generate an RSA Private Key with Passphrase
openssl genrsa -aes256 -out private.key 4096
Generates a 4096-bit RSA private key, encrypts it with AES-256, and prompts for a passphrase.
Extract Public Key from RSA Private Key
openssl rsa -in private.key -pubout -out public.pem
Extracts the public key from private.key and saves it to public.pem.
Generate an ECDSA Private Key (e.g., P-256 curve)
openssl ecparam -genkey -name prime256v1 -out ec_private.key
Generates an Elliptic Curve Digital Signature Algorithm (ECDSA) private key using the P-256 curve.
Extract Public Key from ECDSA Private Key
openssl ec -in ec_private.key -pubout -out ec_public.pem
Extracts the public key from ec_private.key.
Certificate Generation and Management
Generate a Self-Signed Certificate
openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt
Generates a new RSA private key (server.key) and a self-signed certificate (server.crt) valid for 365 days. -nodes means "no DES" - don’t encrypt the private key. You’ll be prompted for details (Common Name, Organization, etc.).
Generate a Certificate Signing Request (CSR)
openssl req -new -newkey rsa:2048 -nodes -keyout mydomain.key -out mydomain.csr
Generates a new RSA private key (mydomain.key) and a CSR (mydomain.csr). This CSR is sent to a Certificate Authority.
View Certificate Information
openssl x509 -in certificate.crt -text -noout
Displays detailed information about the certificate certificate.crt.
Convert Certificate Formats (e.g., PEM to DER)
openssl x509 -in certificate.pem -outform DER -out certificate.der
Converts a PEM-encoded certificate to DER format.
Convert Private Key Formats (e.g., PEM to PKCS#12)
openssl pkcs12 -export -out keystore.p12 -inkey private.key -in certificate.crt
Bundles a private key and its certificate into a PKCS#12 file (keystore.p12), prompting for an export password.
Verify a Certificate Chain
openssl verify -CAfile ca_bundle.crt certificate.crt
Verifies certificate.crt against the chain provided in ca_bundle.crt.
Encryption and Decryption (Symmetric)
Encrypt a File with AES-256 (CBC mode)
openssl enc -aes-256-cbc -salt -in plaintext.txt -out encrypted.bin
Encrypts plaintext.txt using AES-256 in CBC mode, prompting for a passphrase. -salt adds a random salt to the password for better security.
Decrypt a File with AES-256 (CBC mode)
openssl enc -d -aes-256-cbc -in encrypted.bin -out decrypted.txt
Decrypts encrypted.bin using AES-256 in CBC mode, prompting for the passphrase used during encryption. -d stands for decrypt.
List Available Symmetric Ciphers
openssl list -cipher-algorithms
Shows all symmetric encryption algorithms OpenSSL supports.
Hashing
Generate SHA-256 Hash of a File
openssl dgst -sha256 plaintext.txt
Computes the SHA-256 hash of plaintext.txt.
Generate MD5 Hash of a File
openssl dgst -md5 plaintext.txt
Computes the MD5 hash of plaintext.txt.
Verify File Integrity using SHA-256
echo "checksum_value" > checksum.sha256
openssl dgst -sha256 -check checksum.sha256
Compares the calculated SHA-256 hash of files listed in checksum.sha256 against the provided checksums. The checksum.sha256 file should contain lines like SHA256 (filename) = checksum_value.
Digital Signatures
Sign a File with an RSA Private Key
openssl dgst -sha256 -sign private.key -out signature.sha256.sig data.txt
Creates a SHA-256 digest of data.txt, signs it with private.key, and saves the signature to signature.sha256.sig.
Verify a Signature with an RSA Public Key
openssl dgst -sha256 -verify public.pem -signature signature.sha256.sig data.txt
Verifies the signature signature.sha256.sig for data.txt using the public.pem key. Outputs "Verified OK" or "Verification Failure".
Base64 Encoding/Decoding
Encode a File to Base64
openssl base64 -in file.txt -out file.txt.b64
Encodes the contents of file.txt into Base64 and saves it to file.txt.b64.
Decode a Base64 File
openssl base64 -d -in file.txt.b64 -out file.txt.decoded
Decodes file.txt.b64 and saves the result to file.txt.decoded.
Working with TLS/SSL
Test a Remote Server’s SSL/TLS Connection
openssl s_client -connect example.com:443
Connects to example.com on port 443 using SSL/TLS and displays certificate details and allows sending raw data. Press Ctrl+C to exit.
Test a Remote Server’s SSL/TLS Connection with Specific Protocol
openssl s_client -connect example.com:443 -tls1_2
Connects using only TLS version 1.2. Other options include -ssl3, -tls1, -tls1_1, -tls1_3.
View Server Certificate Chain
openssl s_client -showcerts -connect example.com:443 < /dev/null 2>/dev/null | openssl x509 -text -noout
Connects to example.com:443, shows the certificate chain, extracts the first certificate, and prints its details. Input redirection < /dev/null and error redirection 2>/dev/null prevent interactive prompts and hide connection messages.
Common Patterns
Generating a Private Key and CSR for a Web Server
# 1. Generate a private key
openssl genrsa -aes256 -out server.key 4096
# 2. Create a CSR
openssl req -new -key server.key -out server.csr
# (You'll be prompted for details. Ensure Common Name matches your domain.)
# 3. (Optional) View the CSR details
openssl req -in server.csr -text -noout
# 4. (Optional) Create a self-signed certificate for testing
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
This is the standard workflow for obtaining a certificate from a Certificate Authority.
Encrypting and Decrypting Sensitive Files
# Encrypt with a strong password
openssl enc -aes-256-cbc -salt -in sensitive_data.txt -out sensitive_data.enc
# Decrypt later
openssl enc -d -aes-256-cbc -in sensitive_data.enc -out sensitive_data.txt
Uses AES-256-CBC for strong symmetric encryption.
Verifying Downloaded Files
# After downloading a file and its checksum (e.g., sha256sum.txt)
sha256sum -c sha256sum.txt
While sha256sum is often preferred for simple checksum verification, OpenSSL can also do it:
# Assuming sha256sum.txt contains: SHA256 (myfile.zip) = <checksum>
openssl dgst -sha256 -check sha256sum.txt
Converting PEM to PKCS#12 for Java Keystores
openssl pkcs12 -export -out mykeystore.p12 -inkey mydomain.key -in mydomain.crt -certfile intermediate_ca.crt
Combines a private key, server certificate, and intermediate CA certificate into a PKCS#12 file, commonly used by Java applications.
Generating a Diffie-Hellman Parameters File
openssl dhparam -out dhparam.pem 2048
Generates 2048-bit Diffie-Hellman parameters, often used to strengthen TLS cipher suites. This can take a significant amount of time.
Gotchas
-nodesFlag: When generating private keys (genrsa,ecparam), the-nodesflag means "no DES encryption". This results in an unencrypted private key file. While convenient for automated processes or testing, it’s insecure for production environments. Always use a strong passphrase for production private keys.- Key Size: Using key sizes smaller than 2048 bits for RSA is generally considered insecure. 4096 bits is recommended for long-term security.
- Certificate Expiration: Self-signed certificates and certificates issued by CAs have an expiration date. Ensure you have a process for renewing certificates before they expire.
- Common Name (CN) vs. Subject Alternative Name (SAN): For TLS/SSL, modern browsers primarily rely on the Subject Alternative Name (SAN) extension in certificates to match against the domain name. While the Common Name (CN) is still checked, it’s best practice to include the domain(s) in the SAN field during certificate generation (often done via a configuration file with
openssl req). - File Permissions: Private key files (
.key,.pem) should have strict file permissions (e.g.,chmod 600 private.key) to prevent unauthorized access. - Password Prompts: Many OpenSSL commands will prompt for passphrases or passwords. If automating scripts, you might need to find ways to provide these securely (e.g., using
-passin pass:yourpassword- use with extreme caution as passwords become visible in process lists/command history or using environment variables/files with appropriate permissions). - Cipher Suite Compatibility: When using
openssl s_client, be aware that servers might negotiate different cipher suites based on their configuration and your client’s capabilities. Specifying protocols (-tls1_2) can help test specific configurations. - RANDFILE: OpenSSL uses a random number file (
$RANDFILE, often~/.rnd) for generating cryptographically secure random numbers. Ensure this file exists and has appropriate permissions. If it doesn’t exist, OpenSSL might create it or issue warnings.