CloudAcademia
EN

Cybersecurity · Module 05 · Cryptography Basics: Hashing, Encryption and Certificates

Lab: Hashing, Encrypting and Signing with OpenSSL

Lab45 minBeginnerMarkdown

Showing raw Markdown: the renderer could not load.

## Goal
Try every tool from the lesson on a tiny text file with the `openssl` command: hash it, encrypt it with a password, sign it with a key pair, and turn a key into a certificate. Then read the real certificate chain of `example.com`, the way your browser does.

## Objectives
- Compute a SHA-256 digest and see that changing one character changes it completely.
- Encrypt and decrypt a file with a password, and see what happens with a wrong password and with a tampered file.
- Create a key pair, sign a file, verify the signature, and see verification fail after a change.
- Create a self-signed certificate and read its fields.
- Identify the subject, issuer, validity dates and SAN in a real certificate chain.

## Prerequisites
- OpenSSL 3.0 or later. Check it with `openssl version`. It must say `OpenSSL 3.x`, not `LibreSSL` or `1.1.1`.
- A terminal. On Windows, use WSL2.
- Internet access for Step 7 only.
- [The Cryptography Basics lesson](lesson.md) of this module.

> [!WARNING]
> Everything in Steps 1 to 6 happens on your own computer with files you create. Step 7 only **connects to port 443 of `example.com` and reads the certificate it offers**, exactly like a browser does. Don't point `openssl s_client` at systems you don't own or aren't allowed to test, and don't send anything else to them.

> [!NOTE]
> The keys and passwords in this lab are for practice only. Never reuse a lab key for anything real, and never type a real password on a command line: it is visible in the process list and saved in your shell history.

## Architecture
<figure class="diagram" style="--dg-w: 1020px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 1020 330" width="1020" height="330" role="img" aria-labelledby="crypto-lab-architecture-title crypto-lab-architecture-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="crypto-lab-architecture-title">Lab scenario: five openssl exercises in ~/crypto-lab</title>
<desc id="crypto-lab-architecture-desc">On the left, a zone for your computer, folder ~/crypto-lab, with four cards. Step 2, hash: message.txt, with sha256sum and openssl dgst. Steps 3 and 4, encrypt: message.enc, with openssl enc and AES-256-CBC. Step 5, sign: private.pem, public.pem and message.sig using Ed25519. Step 6, certificate: server.crt and server.key, with openssl req and openssl x509. On the right, a read-only zone for the Internet with step 7, the real certificate chain of example.com on port 443, read the way a browser would, using openssl s_client.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="1019" height="329" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<g class="dg-l2"><rect class="dg-tint" x="20" y="20" width="640" height="290" rx="16" fill="#f1f7f3" stroke="#a1ccb1" stroke-width="1.2" stroke-dasharray="6 5"/>
<g class="dg-icon" transform="translate(36 33) scale(0.7500)" fill="none" stroke="#15803d" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="62" y="47" font-size="13" class="dg-ink" fill="#15803d" font-weight="700">Your computer: ~/crypto-lab</text></g>
<rect class="dg-card" x="40" y="62" width="288" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l2"><g class="dg-icon" transform="translate(56 78) scale(1.2500)" fill="none" stroke="#15803d" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="4" x2="20" y1="9" y2="9"/><line x1="4" x2="20" y1="15" y2="15"/><line x1="10" x2="8" y1="3" y2="21"/><line x1="16" x2="14" y1="3" y2="21"/></g></g>
<g class="dg-l2"><text x="98" y="99" font-size="14" class="dg-ink" fill="#15803d" font-weight="700">Step 2: hash</text></g>
<text x="58" y="130" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">message.txt</text>
<text x="58" y="150" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">sha256sum, openssl dgst</text>
<rect class="dg-card" x="346" y="62" width="288" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l2"><g class="dg-icon" transform="translate(362 78) scale(1.2500)" fill="none" stroke="#15803d" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></g></g>
<g class="dg-l2"><text x="404" y="99" font-size="14" class="dg-ink" fill="#15803d" font-weight="700">Steps 3-4: encrypt</text></g>
<text x="364" y="130" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">message.enc</text>
<text x="364" y="150" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">openssl enc, AES-256-CBC</text>
<rect class="dg-card" x="40" y="182" width="288" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l2"><g class="dg-icon" transform="translate(56 198) scale(1.2500)" fill="none" stroke="#15803d" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"/></g></g>
<g class="dg-l2"><text x="98" y="219" font-size="14" class="dg-ink" fill="#15803d" font-weight="700">Step 5: sign</text></g>
<text x="58" y="250" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">private.pem  public.pem</text>
<text x="58" y="270" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">message.sig  (Ed25519)</text>
<rect class="dg-card" x="346" y="182" width="288" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l2"><g class="dg-icon" transform="translate(362 198) scale(1.2500)" fill="none" stroke="#15803d" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></g></g>
<g class="dg-l2"><text x="404" y="219" font-size="14" class="dg-ink" fill="#15803d" font-weight="700">Step 6: certificate</text></g>
<text x="364" y="250" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">server.crt  server.key</text>
<text x="364" y="270" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">openssl req, openssl x509</text>
<g class="dg-l1"><rect class="dg-tint" x="720" y="20" width="280" height="290" rx="16" fill="#f0f6f9" stroke="#9ac3d9" stroke-width="1.2" stroke-dasharray="6 5"/>
<g class="dg-icon" transform="translate(736 33) scale(0.7500)" fill="none" stroke="#0369a1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></g>
<text x="762" y="47" font-size="13" class="dg-ink" fill="#0369a1" font-weight="700">Internet (read-only)</text></g>
<rect class="dg-card" x="736" y="100" width="248" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l1"><g class="dg-icon" transform="translate(752 116) scale(1.2500)" fill="none" stroke="#0369a1" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></g></g>
<g class="dg-l1"><text x="794" y="137" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">Step 7: real chain</text></g>
<text x="754" y="168" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">example.com:443</text>
<text x="754" y="188" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">like a browser would</text>
<g class="dg-l1"><path class="dg-stroke" d="M662 153H718" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M713 147l8 6-8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="836" y="232" font-size="12" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">openssl s_client</text>
</svg></figure>

*Figure 1. Steps 2 to 6 stay on your computer; Step 7 only reads a public certificate.*

## Steps

### Step 1 — Create a working folder and a file (3 min)
You work in one folder so the cleanup at the end is a single command. The file is a tiny "bank instruction" that you will protect in different ways.

```bash
openssl version
mkdir ~/crypto-lab
cd ~/crypto-lab
printf 'Transfer 100 EUR to account ES00 1234\n' > message.txt
cat message.txt
```

What each line does: `openssl version` checks the tool; `mkdir` and `cd` create and enter the folder; `printf` writes one line into `message.txt`; `cat` shows it.

Expected output (the build date after the version differs on your computer, as long as it starts with `OpenSSL 3`):
```text
OpenSSL 3.5.8 25 Aug 2026 (Library: OpenSSL 3.5.8 25 Aug 2026)
Transfer 100 EUR to account ES00 1234
```

### Step 2 — Hash the file and change one character (8 min)
A hash is a fingerprint of the file. Compute it two ways: `sha256sum` (Linux and WSL2; on macOS use `shasum -a 256`) and `openssl dgst`.

```bash
sha256sum message.txt
openssl dgst -sha256 message.txt
```

Expected output:
```text
190fd1598c81d23bd943f4ba864859db3039ab305e60a50bee9bec461d4b092f  message.txt
SHA2-256(message.txt)= 190fd1598c81d23bd943f4ba864859db3039ab305e60a50bee9bec461d4b092f
```

Notice: both tools print the **same 64 hex characters**. Run either command again and you get the same digest every time.

Now make a copy where `100` becomes `900`, and hash it:

```bash
sed 's/100/900/' message.txt > message2.txt
cat message2.txt
sha256sum message2.txt
```

Expected output:
```text
Transfer 900 EUR to account ES00 1234
10bfa161dcd38705488563c4f86395ad2456430fe5b97d08fbbfc8c8322f96c5  message2.txt
```

Compare with the first digest. One character changed in the file, yet the digest looks completely unrelated: that is the **avalanche effect**. The length is still 64 characters.

Finally use the digest the way you would to check a download. Save the digest in a file, then ask `sha256sum` to check the file against it, before and after tampering:

```bash
sha256sum message.txt > SHA256SUMS
sha256sum -c SHA256SUMS
cp message.txt original.txt
cp message2.txt message.txt
sha256sum -c SHA256SUMS
cp original.txt message.txt
sha256sum -c SHA256SUMS
```

`-c` means "check". The two `cp` commands first replace `message.txt` with the changed version (pretending an attacker did it) and then restore it.

Expected output (the words are translated in other languages):
```text
message.txt: OK
message.txt: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
message.txt: OK
```

<details>
<summary>Question: does a matching digest prove the file is from the real author?</summary>

No. It proves the file is the same as the one that was hashed. If an attacker can change the file, they can change `SHA256SUMS` too. To prove **who** made the file you need a key: that is the signature you create in Step 5.

</details>

### Step 3 — Encrypt and decrypt with a password (8 min)
Now confidentiality. `openssl enc` encrypts a file with AES-256 and a key made from your password. The option `-pbkdf2 -iter 600000` makes openssl turn the password into a key with PBKDF2, slowly, and `-salt` adds a random salt (this is the lesson's password-hashing idea again).

```bash
openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt -pass pass:correct-horse -in message.txt -out message.enc
wc -c message.enc
xxd message.enc
```

`-pass pass:correct-horse` gives the password on the command line, which is fine for a lab only (see the note above). `wc -c` counts the bytes. `xxd` shows the file as hexadecimal, because ciphertext is not readable text.

Expected output (everything after `Salted__` varies on every run, because the salt is random):
```text
64 message.enc
00000000: 5361 6c74 6564 5f5f 1865 220a 69f3 72b9  Salted__.e".i.r.
00000010: f14c 9111 b8a4 ce73 cd80 41b5 21c6 2ab0  .L.....s..A.!.*.
00000020: b186 557a af33 e545 2692 f807 cd4b 02ef  ..Uz.3.E&....K..
00000030: 9582 5a70 821b b6e4 ff27 f526 190c 0762  ..Zp.....'.&...b
```

Notice: the file starts with the word `Salted__` and 8 bytes of salt, and the rest looks random. The original text is not visible. It is 64 bytes: 8 for `Salted__`, 8 for the salt, and 48 for the encrypted data (the 38-byte message is padded up to a multiple of 16).

Decrypt it with the right password:

```bash
openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -pass pass:correct-horse -in message.enc
```

`-d` means decrypt. You must give the **same** cipher and `-iter` value.

Expected output:
```text
Transfer 100 EUR to account ES00 1234
```

Now try a wrong password. Send the output to a file, because a wrong key produces garbage:

```bash
openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -pass pass:wrong-guess -in message.enc -out bad.txt
rm bad.txt
```

Expected output (the hex code at the start of the second line varies):
```text
bad decrypt
00332243777F0000:error:1C800064:Provider routines:ossl_cipher_unpadblock:bad decrypt:providers/implementations/ciphers/ciphercommon_block.c:107:
```

Notice: the wrong password doesn't reveal anything; you get an error. The `rm` removes the garbage file that was left.

> [!NOTE]
> The error is not guaranteed. With this mode, about 1 wrong password in 256 happens to produce valid padding, so `openssl` prints no error and the output is garbage. The mode has no way to say "this key is wrong". Step 4 shows a bigger weakness of the same kind.

### Step 4 — Why you want authenticated encryption (6 min)
The lesson says AES-CBC gives no integrity. Check it. The command below changes **one byte** in the middle of `message.enc`, as an attacker could. `dd` overwrites the byte at position 32 with zero.

```bash
cp message.enc tampered.enc
printf '\000' | dd of=tampered.enc bs=1 seek=32 conv=notrunc 2>/dev/null
openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -pass pass:correct-horse -in tampered.enc -out tampered.txt
echo "exit code: $?"
xxd tampered.txt
```

Expected output (the garbled bytes on the second line and the changed byte at the start of the third line vary, because the salt is random):
```text
exit code: 0
00000000: 5472 616e 7366 6572 2031 3030 2045 5552  Transfer 100 EUR
00000010: 63a6 2f97 15ae 6556 aa6a 448b 2a17 3791  c./...eV.jD.*.7.
00000020: 9131 3233 340a                           .1234.
```

Notice three things. The command says **success** (exit code 0). The first 16 characters are fine. The next 16 are garbage, and the space at the start of the last line (before `1234`) was replaced by another byte. OpenSSL didn't detect the tampering: this is why modern protocols use **authenticated** encryption (AEAD) such as AES-GCM, which fails if even one bit changes.

Ask `openssl enc` to use one:

```bash
openssl enc -aes-256-gcm -pbkdf2 -pass pass:x -in message.txt -out /dev/null
```

Expected output:
```text
enc: AEAD ciphers not supported
enc: Use -help for summary.
```

This is an honest limit of the tool: `openssl enc` can't do AES-GCM. It is good for learning, not for protecting real data. For real files use a maintained tool built on authenticated encryption, such as `age` or GnuPG, and in your programs a library that provides AES-GCM or ChaCha20-Poly1305.

<details>
<summary>Question: why did decryption "succeed" with a damaged file?</summary>

CBC only turns blocks of bytes back into plaintext. It has no check value (no MAC, no tag), so it can't know the ciphertext was changed. The damage shows up as garbage in the block after the changed byte, plus a flipped byte in the next block. An AEAD mode adds an authentication tag and refuses to decrypt if the tag doesn't match.

</details>

### Step 5 — Sign a file and verify the signature (8 min)
Now authenticity. You create a **key pair** with the Ed25519 algorithm, sign `message.txt` with the **private** key, and check it with the **public** key.

```bash
openssl genpkey -algorithm ED25519 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem
cat public.pem
```

`genpkey` generates the private key. `pkey -pubout` derives the public key from it. Only the public key is meant to be shared.

Expected output (your key text is different):
```text
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAVPF2/34u81ANojBZJ/uT7OQ+7sX3ui2HiaKGVgG8t98=
-----END PUBLIC KEY-----
```

Look at the private key file permissions. On Linux, OpenSSL creates it readable only by you:

```bash
ls -l private.pem
```

Expected output (the owner, date and extra characters vary):
```text
-rw------- 1 user user 119 Nov  7 20:40 private.pem
```

`-rw-------` means only you can read and write it. A private key must always be like that.

Sign the message:

```bash
openssl pkeyutl -sign -inkey private.pem -rawin -in message.txt -out message.sig
wc -c message.sig
```

`pkeyutl -sign` signs with the private key. `-rawin` tells it to take the whole file as input. Ed25519 hashes the file inside the algorithm, so you don't hash it first.

Expected output:
```text
64 message.sig
```

An Ed25519 signature is always 64 bytes, however large the file is. Now verify with the **public** key:

```bash
openssl pkeyutl -verify -pubin -inkey public.pem -rawin -in message.txt -sigfile message.sig
```

`-pubin` says the key you give is a public key.

Expected output:
```text
Signature Verified Successfully
```

Now try to verify the same signature against the **changed** file, `message2.txt` (the 900 EUR one):

```bash
openssl pkeyutl -verify -pubin -inkey public.pem -rawin -in message2.txt -sigfile message.sig
```

Expected output (the code at the start of the first line varies):
```text
005364386B7F0000:error:030000EA:digital envelope routines:EVP_DigestVerify:provider signature failure:crypto/evp/m_sigver.c:795:ED25519 digest_verify:
Signature Verification Failure
```

Notice: one changed character and the signature no longer matches. Nobody can fix it without the private key. Unlike the hash in Step 2, an attacker can't replace the signature to match a tampered file.

<details>
<summary>Question: who needs the private key, and who needs the public key?</summary>

The **signer** needs the private key, to create signatures. **Everybody who wants to verify** needs the public key. That's why you can publish the public key freely and must protect the private key. The remaining question, "is this really the public key of the author?", is answered by certificates, in the next step.

</details>

### Step 6 — Create a self-signed certificate and read it (7 min)
A certificate binds a public key to a name. One command creates a new key pair and a **self-signed** certificate (signed by its own key, with no CA) for a made-up name on the reserved `example.org` domain, valid for 30 days.

```bash
openssl req -x509 -newkey ed25519 -nodes -keyout server.key -out server.crt -days 30 \
  -subj "/CN=lab.example.org/O=CloudAcademia Lab" -addext "subjectAltName=DNS:lab.example.org"
```

What the options mean: `req -x509` makes a certificate instead of a request; `-newkey ed25519` makes a new key; `-nodes` leaves the private key unencrypted (lab only); `-keyout` and `-out` name the files; `-days 30` sets the validity; `-subj` sets the name fields; `-addext` adds the SAN.

Expected output:
```text
-----
```

Read the certificate fields you learned in the lesson:

```bash
openssl x509 -in server.crt -noout -subject -issuer -dates -ext subjectAltName,basicConstraints
```

Expected output (the dates are 30 days apart, starting when you ran the command):
```text
subject=CN=lab.example.org, O=CloudAcademia Lab
issuer=CN=lab.example.org, O=CloudAcademia Lab
notBefore=Nov  7 19:40:39 2026 GMT
notAfter=Dec  7 19:40:39 2026 GMT
X509v3 Basic Constraints: critical
    CA:TRUE
X509v3 Subject Alternative Name: 
    DNS:lab.example.org
```

Notice: **subject and issuer are identical**. That's what "self-signed" means. To see everything, including the public key and the signature, print the full text:

```bash
openssl x509 -in server.crt -noout -text
```

Expected output (trimmed; serial number, key and signature bytes vary):
```text
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            7f:8f:86:e8:fe:a8:69:a8:09:be:68:86:59:17:31:37:61:10:f1:7d
        Signature Algorithm: ED25519
        Issuer: CN=lab.example.org, O=CloudAcademia Lab
        Validity
            Not Before: Nov  7 19:40:39 2026 GMT
            Not After : Dec  7 19:40:39 2026 GMT
        Subject: CN=lab.example.org, O=CloudAcademia Lab
        Subject Public Key Info:
            Public Key Algorithm: ED25519
                ED25519 Public-Key:
                pub:
                    a7:11:42:5a:60:88:0d:5f:6b:41:97:23:f1:ba:5d:
                    ...
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                84:24:8A:08:11:DC:3E:B5:44:DF:38:19:3B:90:9F:73:58:49:EA:D5
            X509v3 Authority Key Identifier: 
                84:24:8A:08:11:DC:3E:B5:44:DF:38:19:3B:90:9F:73:58:49:EA:D5
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Subject Alternative Name: 
                DNS:lab.example.org
    Signature Algorithm: ED25519
    Signature Value:
        76:9f:98:3e:86:ac:f9:27:2b:f6:78:4d:56:2a:33:94:14:c3:
        ...
```

Find each field: Serial Number, Issuer, Validity, Subject, Subject Public Key Info, extensions (SAN, Basic Constraints) and the issuer's Signature.

Now see why browsers don't trust it. Ask OpenSSL to verify it against your computer's list of trusted roots, and then against itself:

```bash
openssl verify server.crt
openssl verify -CAfile server.crt server.crt
```

Expected output:
```text
CN=lab.example.org, O=CloudAcademia Lab
error 18 at 0 depth lookup: self-signed certificate
error server.crt: verification failed
server.crt: OK
```

Notice: the first check fails because no CA in your **root store** vouches for this certificate. The second passes only because you told OpenSSL to trust this exact certificate yourself. A browser's trust is the same idea with about a hundred roots already installed.

### Step 7 — Read the real certificate chain of example.com (5 min)
This step needs the Internet. `openssl s_client` opens a TLS connection like a browser. `-servername example.com` sends the server name so the server picks the right certificate. `</dev/null` ends the session at once, so nothing else is sent.

```bash
openssl s_client -connect example.com:443 -servername example.com </dev/null > chain.txt 2>&1
sed -n '/^Certificate chain/,/^---/p' chain.txt
```

The first command saves the whole output in `chain.txt`; `sed` prints only the chain section.

> [!NOTE]
> This is a real website, so **your output will differ from the one below**: the certificate is renewed every few weeks or months, and the certificate authorities, chain length and algorithms can change. Look for the same kinds of information, not the same values.

Expected output (shortened to the first two certificates; your list can be shorter or longer):
```text
Certificate chain
 0 s:CN=example.com
   i:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
   a:PKEY: EC, (prime256v1); sigalg: ecdsa-with-SHA256
   v:NotBefore: Sep 26 22:49:11 2026 GMT; NotAfter: Dec 25 22:56:35 2026 GMT
 1 s:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
   i:C=US, O=SSL Corporation, CN=SSL.com TLS Transit ECC CA R2
   a:PKEY: EC, (prime256v1); sigalg: ecdsa-with-SHA384
   v:NotBefore: May 29 19:49:45 2025 GMT; NotAfter: May 27 19:49:44 2035 GMT
 ...
---
```

Read it like this: `s:` is the **subject** and `i:` is the **issuer**. Certificate 0 is the **leaf** for `example.com`, issued by the intermediate CA that is certificate 1. Each certificate's issuer is the subject of the next one: that is the chain. `v:` gives the validity dates. The last certificates in the list are the CAs above the intermediate.

Now see what the connection used and whether your computer trusted it:

```bash
grep -E "Protocol|Cipher is|Verification:" chain.txt
```

Expected output:
```text
Verification: OK
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Protocol: TLSv1.3
```

Notice: **TLS 1.3** with an **AES-GCM** cipher, the hybrid from the lesson. `Verification: OK` means the chain ends in a root that is in your root store. Your values can differ (for example `TLS_AES_128_GCM_SHA256`).

Finally read the leaf certificate's details with the `x509` command you used in Step 6. `openssl x509` reads the first certificate in the file, the leaf:

```bash
openssl x509 -in chain.txt -noout -subject -issuer -dates -ext subjectAltName
```

Expected output:
```text
subject=CN=example.com
issuer=C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
notBefore=Sep 26 22:49:11 2026 GMT
notAfter=Dec 25 22:56:35 2026 GMT
X509v3 Subject Alternative Name: 
    DNS:example.com, DNS:*.example.com
```

Answer these questions with **your** output:

1. Who is the subject and who is the issuer of the leaf certificate?
2. For how many days is the certificate valid?
3. Which names does the SAN list? Would the certificate be valid for `www.example.com`? And for `a.b.example.com`?

<details>
<summary>Show the answers (for the output above)</summary>

1. The subject is `CN=example.com`; the issuer is the intermediate CA `Cloudflare TLS Issuing ECC CA 3`.
2. From Sep 26 to Dec 25 2026: about 90 days. Public certificates are short-lived, as the lesson explains.
3. `example.com` and `*.example.com`. `www.example.com` matches the wildcard. `a.b.example.com` doesn't: a wildcard covers one label only.

Your own answers will differ, but the method is the same: read subject, issuer, `NotBefore` and `NotAfter`, and the SAN.

</details>

## Verification
Check that you got the key results. All of these must be true:

```bash
sha256sum -c SHA256SUMS
openssl pkeyutl -verify -pubin -inkey public.pem -rawin -in message.txt -sigfile message.sig
openssl verify -CAfile server.crt server.crt
```

Expected output:
```text
message.txt: OK
Signature Verified Successfully
server.crt: OK
```

You pass if:
- the digest of the original file matches (`OK`) and the changed file gave a different digest in Step 2;
- the right password decrypted the file and a wrong one gave `bad decrypt`;
- the signature verified for `message.txt` and failed for `message2.txt`;
- you could point to the subject, issuer, validity dates and SAN of `example.com` in Step 7.

## Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `openssl version` says `LibreSSL` or `OpenSSL 1.1.1`, or `pkeyutl` doesn't know `-rawin` | An older or different OpenSSL (the macOS default is LibreSSL) | Use OpenSSL 3.0 or later: install it (for example with Homebrew on macOS) or use WSL2 on Windows |
| `Signature Verification Failure` in Step 5 for `message.txt` | You edited `message.txt` after signing, or you signed another file | Redo `openssl pkeyutl -sign` on the current `message.txt`. The failure for `message2.txt` is expected |
| `bad decrypt` when decrypting with the right password | A different `-iter` or cipher than when encrypting, or a typo in the password | Use exactly the same options and password as in the encrypt command |
| `error 18 ... self-signed certificate` from `openssl verify server.crt` | Expected: no trusted CA signed it | Use `-CAfile server.crt` as in Step 6 to trust it explicitly |
| `connect: Connection refused`, `Connection timed out` or `getaddrinfo` errors in Step 7 | No Internet access, or a firewall or proxy blocks port 443 | Check your connection and try again; a proxy can change the chain you see. Skip Step 7 if the network is restricted |
| `sha256sum: command not found` on macOS | macOS has `shasum` instead | Use `shasum -a 256 message.txt` |
| The `Verification:` line is missing or says an error | Your computer has no CA bundle, or its clock is wrong | Check the system date and install the CA certificates package of your system |

## Challenge (optional)
1. Repeat Step 3 with **no** `-iter` option, and with `-iter 1000`. Decrypt each. Why does the iteration count matter for a password, and what do you have to remember at decryption time?
2. Generate an RSA key pair with `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa-key.pem`, derive its public key as in Step 5 (name it `rsa.pub`), and sign `message.txt` with `openssl pkeyutl -sign -inkey rsa-key.pem -rawin -digest sha256 -in message.txt -out rsa.sig`. Verify it the same way (add `-digest sha256` to the verify command too). Compare the signature size and the public-key file size with the Ed25519 ones (hint: 384 bytes against 64).
3. In Step 7, connect to `example.org` instead and compare the chain, the issuer and the SAN with `example.com`.

## Cleanup
The lab created one folder in your home directory and nothing else. Remove it, with the keys inside:

```bash
cd ~
rm -r ~/crypto-lab
```

Check that it's gone:

```bash
ls ~/crypto-lab
```

Expected output:
```text
ls: cannot access '/home/<you>/crypto-lab': No such file or directory
```

Nothing was installed and no system trust store was changed.

## What you learned
- A hash is a fixed-size, repeatable fingerprint: one changed character gives a completely different digest. It shows integrity, but anyone can recompute it, so it doesn't prove who wrote the file.
- Password encryption with `openssl enc` hides the content, but CBC mode can't detect tampering. Prefer authenticated encryption (AES-GCM, ChaCha20-Poly1305) through a proper library or tool.
- A signature made with a private key is verified with the public key and breaks when the file changes. Keep the private key private (`600` permissions).
- A certificate binds a name (the SAN) to a public key; a self-signed one isn't trusted by anybody unless you say so, while a real one chains to a root in the root store.
- `openssl s_client` shows what your browser sees: the chain, the validity dates, the TLS version and the cipher.