Tools · Cryptography and passwords in practice · 01 / 20
OpenSSL command line for beginners: hashes, random bytes, keys, and encryption
Learn the OpenSSL subcommands you will use most: dgst for hashes, rand for random data, genpkey for keys, and enc for file encryption with a proper key derivation function.
Know your version
OpenSSL 3.x is the current major line and changed several defaults compared with 1.1.1. LibreSSL on macOS behaves slightly differently. Run openssl version -a first, because flags and supported algorithms depend on it.
Everyday subcommands
openssl dgst computes digests and HMACs. openssl rand produces cryptographically secure random bytes. openssl genpkey creates private keys for RSA, EC, Ed25519, and X25519. openssl pkey reads and converts keys. openssl enc performs symmetric encryption; always use -pbkdf2 with a high iteration count when the key comes from a password, because the old default derivation was weak.
openssl version -a openssl dgst -sha256 report.pdf openssl dgst -sha256 -hmac 'lab-secret' message.txt openssl rand -hex 32 openssl genpkey -algorithm ed25519 -out ed25519.key openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key openssl pkey -in rsa.key -pubout -out rsa.pub openssl pkey -in rsa.key -text -noout | head
Lab: encrypt and decrypt a file
Encrypt a test file with AES-256-CBC using PBKDF2, then decrypt it and compare hashes. Try decrypting with a wrong password and observe the “bad decrypt” error. Note that openssl enc does not support authenticated modes like GCM for files, so it cannot detect tampering on its own; for real file encryption, prefer tools such as age or GPG, covered in other lessons.
echo 'lab data only' > plain.txt openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt -in plain.txt -out plain.enc openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -in plain.enc -out roundtrip.txt sha256sum plain.txt roundtrip.txt xxd plain.enc | head -2 # starts with Salted__
Pitfalls
Forgetting -pbkdf2 produces a file encrypted with a weak, legacy key derivation. Passing passwords on the command line with -pass pass:... exposes them in shell history and process lists; use -pass file: or an environment variable in labs. Do not use MD5 or SHA-1 for anything security-relevant.
Diagram
OpenSSL subcommands
Most tasks use one of these.
- dgst
Hashes and HMACs: -sha256, -hmac.
- rand
Secure random bytes: -hex 32.
- genpkey / pkey
Create, inspect, and convert private and public keys.
- enc
Symmetric file encryption; always add -pbkdf2.
- x509 / req / s_client
Certificates, signing requests, and TLS testing.
Check yourself
1. Which command produces 32 secure random bytes as hex?
2. Which flag should always accompany password-based openssl enc encryption?
3. Why is openssl enc with CBC not ideal for protecting files against tampering?