Lesson 05 · 60 minutes
Encrypt, sign and verify a file with OpenSSL
- Say what a hash, an encryption key, a signature and a certificate each prove
- Encrypt and decrypt a file with AES-256 and make a key pair
- Sign a file, verify it, and see the check fail after a one-byte change
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team lead forwards three copies of a short update notice, "Update to version 4.1 before Friday", and a signature that the author sent in a separate mail. Two copies came through a chat tool, and nobody can say which one is the original. A second mail holds an encrypted note with the location of a spare key. Your task: find out which copy is authentic, and read the note. You get the author's public key and the passphrase for the note by phone.
Recall
Lesson 2: why does a hash file next to the file not stop an attacker who can write to the folder?
The attacker changes the file and writes a new hash beside it, so the check passes. A hash alone proves nothing about who made it. A signature closes this gap, and this lesson shows how.
Lesson 3: why do we hash a password with a slow function and a salt?
The slow function makes each guess expensive. The salt makes each hash unique, so one precomputed table cannot serve all users.
The idea
| Tool | In plain words | What it proves |
|---|---|---|
| Hash | A fingerprint of data. No key. | The data is the same as when the fingerprint was made. |
| Symmetric encryption | One secret key locks and unlocks. | Nobody without the key can read the data. |
| Asymmetric key pair | A private key that you keep and a public key that you share. | The private key signs, and the public key checks. Nobody can make a signature that the public key accepts without the private key. |
| Signature | Proof, made from the exact data with the private key, that anyone who has the public key can check. | The holder of the private key made it, and it has not changed. |
| Certificate | A public key with a name, signed by someone that you trust. | This key belongs to this name. |
| TLS | The protocol of HTTPS. The server proves its name with its certificate, and both sides agree a fresh secret key. | A secret channel to a server with a proven name, and no change on the way. |
Two limits matter. A hash alone does not stop an attacker, who can change the data and make a new hash. Encryption hides data, but plain encryption does not detect a change. Real programs use authenticated encryption (AES-GCM or ChaCha20-Poly1305) from a library. openssl enc is used here to show the idea.
Some key pairs (RSA) can also encrypt: anyone locks a message with the public key, and only the private key opens it. TLS does not need that. The two sides agree a fresh secret key by an exchange that an eavesdropper cannot follow, the certificate key signs that exchange to prove the server's name, and then fast symmetric encryption protects the traffic.
The first rule of the subject: never invent your own cryptography. Do not write your own cipher, and do not join good parts into your own scheme. Use a tested tool, a current algorithm and a library's default. Experts break home-made schemes quickly.
This is how a signature protects a file on its way:
- Author → Private key: sign the file
- Author → Verifier: the file and its signature
- Verifier → Public key: check the signature: it passes
- Attacker → Verifier (blocked): a changed file, the same signature
Worked example
You work on your own files with openssl, a toolkit for cryptography that most Linux machines already have.
1. Prepare a message and hash it
openssl dgst -sha256 prints the SHA-256 hash of a file (dgst is short for digest, another word for hash).
mkdir -p ~/krlab/security-basics/crypto
cd ~/krlab/security-basics/crypto
echo "meet at the old bridge at noon" > message.txt
openssl dgst -sha256 message.txtSHA2-256(message.txt)= 14d32333d0f9748428e2a455ec0b46fbaca9628b84fb50545acf5ee64ded48892. Encrypt with AES-256
openssl enc encrypts a file. -aes-256-cbc picks the cipher: AES with a 256-bit key. -salt adds a random salt, and -pbkdf2 turns your passphrase into a key with a slow, salted function (lesson 3). Without -pbkdf2, OpenSSL uses an old, weak derivation. export sets an environment variable, a named value that programs can read. The passphrase goes into a variable and -pass env:KRPASS reads it, so that the passphrase does not appear in the list of processes. xxd shows the bytes of a file in hex.
export KRPASS='correct horse battery'
openssl enc -aes-256-cbc -pbkdf2 -salt -in message.txt -out message.enc -pass env:KRPASS
xxd message.enc | head -200000000: 5361 6c74 6564 5f5f e674 1ff8 daff f876 Salted__.t.....v
00000010: b4a9 5bef 9fae b9b9 a33a 1762 0420 3174 ..[......:.b. 1tThe file starts with the word Salted__ and the random salt, then the unreadable data. Your bytes will differ.
3. Decrypt, with the right and the wrong passphrase
-d turns the command round: it decrypts. The second command sets a wrong passphrase for that one command, and > /dev/null throws away its normal output, so that only the error shows.
openssl enc -d -aes-256-cbc -pbkdf2 -in message.enc -pass env:KRPASS
KRPASS=wrong openssl enc -d -aes-256-cbc -pbkdf2 -in message.enc -pass env:KRPASS > /dev/nullmeet at the old bridge at noon
bad decryptThe second line is shortened: OpenSSL adds an error code. A wrong key usually fails the padding check, but not always, which is why encryption alone cannot tell you that the data is intact.
4. Make a key pair
Ed25519 is a modern signature algorithm. openssl genpkey makes a private key, and openssl pkey -pubout computes the matching public key from it. The brackets run the commands in a subshell with umask 077, so the new files are private from the start and your own umask stays as it was (lesson 4).
(umask 077; openssl genpkey -algorithm ed25519 -out private.pem; openssl pkey -in private.pem -pubout -out public.pem)
ls -l private.pem public.pem-rw------- 1 you you 119 Nov 21 08:36 private.pem
-rw------- 1 you you 113 Nov 21 08:36 public.pemYou may share public.pem. Never share private.pem.
5. Sign the file and verify it
openssl pkeyutl -sign makes a signature with a private key. -rawin says that the input is the whole file and not a ready hash. pkeyutl -verify checks a signature with a public key (-pubin says that the key is a public one).
openssl pkeyutl -sign -rawin -inkey private.pem -in message.txt -out message.sig
openssl pkeyutl -verify -rawin -pubin -inkey public.pem -in message.txt -sigfile message.sigSignature Verified Successfully6. Send the signature as text
A signature is binary, and a mail holds text. base64 turns bytes into plain letters and digits, and base64 -d turns them back. The decoded file is the same as the original, and cmp (compare) prints nothing when two files are the same. The sign && runs the next command only when the one before succeeded.
base64 message.sig > message.sig.b64
cat message.sig.b64
base64 -d message.sig.b64 > again.sig
cmp message.sig again.sig && echo sameydzqLi8vdEba/M7Vmid5MgzP1DubaxF83ZdMlr4McCy+4lsGgppC4DTYvYJ/QcHeYjb1qYGH5jiI
Y67VD56fBw==
sameYour text will differ, because your key is new.
7. Change one byte and verify again
sed 's/meet/Meet/' changes the first letter to a capital. cmp then shows that exactly one byte differs.
sed 's/meet/Meet/' message.txt > tampered.txt
cmp message.txt tampered.txt
openssl pkeyutl -verify -rawin -pubin -inkey public.pem -in tampered.txt -sigfile message.sig
echo "exit code: $?"message.txt tampered.txt differ: byte 1, line 1
Signature Verification Failure
exit code: 1OpenSSL also prints an error line before the result. One byte broke the proof. Anyone with public.pem can run this check, and nobody can make a valid signature for the new text without private.pem.
8. Look at a certificate
openssl req -x509 makes a self-signed certificate for a test name. -newkey ed25519 makes a new key of that type, -keyout names the key file, -out names the certificate file, -subj gives the name, and -days 30 sets the life of the certificate. -nodes leaves the key without a passphrase: that is fine for a test and wrong for a real key. openssl x509 -noout prints chosen fields of a certificate. In a self-signed certificate the subject and the issuer are the same: it vouches for itself, so a browser would not trust it.
openssl req -x509 -newkey ed25519 -nodes -keyout cert.key -out cert.pem -subj "/CN=krbox.local" -days 30
openssl x509 -in cert.pem -noout -subject -issuer -dates-----
subject=CN=krbox.local
issuer=CN=krbox.local
notBefore=Nov 21 08:37:00 2026 GMT
notAfter=Dec 21 08:37:00 2026 GMTThe first line, a row of dashes, is OpenSSL's own mark. Ignore it.
A real certificate has an issuer that your system already trusts (a certificate authority).
9. Use the certificate in a TLS connection
This step is optional deepening: skip it if you are tired, and the Your turn still works. Both programs run on your own machine only (127.0.0.1). openssl s_server is a small test server that speaks TLS, and -www makes it answer with a simple page. openssl s_client is a TLS client: -brief prints a short summary, and < /dev/null gives it empty input, so that it ends after the handshake.
Three shell parts help. The & at the end of the first command runs the server in the background, and sleep 1 waits one second for it to start. grep -E keeps the lines that matter. The server listens until the last line stops it: kill $! ends it ($! is the process number of the last background program), so do not skip that line. Port 8643 is free on most machines. If nothing prints, run cat server.log: it may say that the port is in use, so change 8643 to another number in both commands.
openssl s_server -accept 8643 -cert cert.pem -key cert.key -www > server.log 2>&1 &
sleep 1
openssl s_client -connect 127.0.0.1:8643 -brief < /dev/null 2>&1 | grep -E "^(verify error|Protocol|Ciphersuite|Peer cert|Signature type|Verification)"
kill $!verify error:num=18:self-signed certificate
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: CN=krbox.local
Signature type: ed25519
Verification error: self-signed certificate- s_client → s_server: hello and a fresh temporary key
- s_server → s_client: its temporary key and the certificate
- s_server → s_client: a signature proves the name krbox.local
- s_client: no trusted signer: self-signed
- s_client → s_server: traffic under TLS_AES_256_GCM_SHA384
The line Signature type: ed25519 is the certificate key at work: an Ed25519 key can only sign, so it did not lock the secret key. The two sides made fresh temporary keys for that, and the signature proved the server's name.
The client reported that it cannot trust the certificate, as a browser does on a site with a self-signed certificate. On a real site a certificate authority has signed the certificate, the check passes, and you know that you talk to the right server and that nobody read or changed the traffic. Your cipher name can differ. The Networking course, lesson 9, goes through the handshake and the certificate chain in full.
Your turn
Do the task of your team lead, with the tools of the worked example. Work in a new folder, ~/krlab/security-basics/notice. Make the three copies with echo, each holding one line (the line end that echo adds is part of the file):
| File | Its line |
|---|---|
notice-a.txt | Update to version 4.2 before Friday. |
notice-b.txt | Update to version 4.1 before Friday. |
notice-c.txt | Update to version 4.1 before friday. |
The author's public key, saved as author.pem:
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAUavak0vOXCkG6MqXQcmIXiEsthqAIgdKmCrEeYr46CQ=
-----END PUBLIC KEY-----Both of the next two items are base64 text: decode each one into a file with base64 -d (step 6) before you verify or decrypt it. The signature, as one line of base64:
HSqM6MopNWSYwMuJP3Q2brPevfEHjkYxhLAnqw6bt5eAwVYkuTSixX7DFtaHodBWRDYs0GZie6mu0BgnvtB1BA==The encrypted note, as one line of base64. The author says the passphrase is river stone 91, and that the cipher is the one of the worked example:
U2FsdGVkX1/IDo5xDdVxxRHKmHd5dDOSgePKASV4xbTFOsv8Dy0xtYwDaV7iY3mxJPCdTjWkSn33Jgwa8QblSw==Last, change one character of the valid copy and prove that the signature fails.
Check yourself
You download a program and its SHA-256 hash from the same web page. What does a match prove?
Only that the download was not damaged on the way. If an attacker controls the page, they can replace both. A signature checked with a public key that you got by another route proves much more.
Why can everyone check your signature but nobody can forge it?
Checking needs only the public key, which is public. Making a signature needs the private key, which only you hold.
A site sends you a certificate. What does the certificate prove that a bare public key does not?
It ties the key to a name, and a party that you trust has signed that tie. A bare key says nothing about who owns it.
Field notes
openssl encwith CBC has no authentication, so someone can change the data in a way that you do not detect. In programs, let a vetted library pick the nonce for authenticated encryption.- Password-based keys are only as strong as the passphrase. A high iteration count slows guessing:
-iterraises it above the default of 10,000, and OWASP gives current minimum counts for PBKDF2. - Protect the private key: a file mode of
600, a passphrase on the key (openssl genpkey -aes256), and a hardware token for keys that matter. Rotate a key when you doubt it. A leaked signing key cannot be called back. - TLS certificates follow RFC 5280 (X.509). Use
openssl s_client -connect host:443against hosts that you own to inspect the chain, and check expiry dates with monitoring, because expired certificates cause many outages. - NIST SP 800-57 covers key management, and NIST SP 800-131A lists which algorithms and key sizes are still approved. Avoid MD5 and SHA-1 for anything that must resist an attacker.