Mohamud's Labs

Cryptographic Keys in Practice: Symmetric, Asymmetric, Derived and Session Keys

A hands-on tour of the main types of cryptographic keys: symmetric, asymmetric (RSA, ECDSA, Ed25519), password-derived, session keys and key pairs used for signing, SSH and PGP. You generate, inspect, use and compare each type, then look at how keys are stored and rotated.

IntermediateUpdated

Authorized environments only. Every lab runs in an isolated environment I own. Never test systems you don't have written permission to test.

Scenario

A small team is reviewing how it uses cryptography. People say "the key" as if there were only one kind, but a single web login can involve a password-derived key, a TLS session key, a server certificate key and an SSH key for deployment. Mixing them up leads to real mistakes: sharing a private key, using a weak key size, or storing a key next to the data it protects.

In this lab you build a clear mental model by generating and using every major key type yourself, on an isolated machine, and comparing what each one is for, how big it is, and how it fails.

Objectives

By the end of this lab you will be able to:

  1. Explain the difference between symmetric and asymmetric keys, and say when each is used.
  2. Generate and use a symmetric key (AES-256) to encrypt and decrypt a file.
  3. Derive a key from a password with a key derivation function (KDF) and explain why salts and iteration counts matter.
  4. Generate RSA, ECDSA and Ed25519 key pairs and compare their sizes and formats.
  5. Sign and verify data with a private/public key pair.
  6. Perform a key exchange to produce a shared session key.
  7. Create and inspect SSH and PGP keys, including passphrase protection and fingerprints.
  8. Describe key storage, rotation and revocation practices.

Environment

  • One Linux VM (Ubuntu 22.04 or later, or Debian 12), no inbound network access needed.
  • Tools: openssl (3.x), openssh-client, gnupg, xxd.
  • Work in a throwaway directory so nothing here is mistaken for real keys:
bash
mkdir -p ~/keys-lab && cd ~/keys-lab
openssl version
ssh -V
gpg --version | head -n 1

Important: every key created here is for learning only. Never reuse them for real systems, and delete the directory when you finish.

Steps

Step 1. Symmetric keys: one secret, shared by both sides

A symmetric key is a single secret used for both encryption and decryption. It is fast and ideal for bulk data, but both parties must already share it safely.

Generate a random 256-bit key and a 128-bit initialisation vector (IV):

bash
openssl rand -hex 32 > aes.key
openssl rand -hex 16 > aes.iv
wc -c aes.key aes.iv

The key file is 65 bytes: 64 hex characters (32 bytes of key material) plus a newline. The IV is 33 bytes.

Encrypt and decrypt a file with AES-256-CBC:

bash
echo "Quarterly report: confidential" > secret.txt
openssl enc -aes-256-cbc -K $(cat aes.key) -iv $(cat aes.iv) -in secret.txt -out secret.enc
openssl enc -d -aes-256-cbc -K $(cat aes.key) -iv $(cat aes.iv) -in secret.enc

Now try decrypting with one hex digit of the key changed:

bash
openssl enc -d -aes-256-cbc -K $(cat aes.key | sed 's/^./0/') -iv $(cat aes.iv) -in secret.enc

Expect a "bad decrypt" error or garbage output. Record which one you get.

Key points to note:

  • The key length decides the strength: 128, 192 or 256 bits for AES.
  • The IV is not secret, but must be unique per encryption. Reusing a key and IV together is a classic failure.
  • CBC gives confidentiality only. Real systems prefer authenticated modes such as AES-GCM or ChaCha20-Poly1305, which also detect tampering.

Step 2. Derived keys: turning a password into a key

People do not remember 256 random bits, so systems derive keys from passwords using a KDF. A good KDF is deliberately slow and uses a random salt.

bash
openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt -in secret.txt -out secret.pw.enc

Enter a passphrase when prompted. Then inspect the start of the file:

bash
xxd secret.pw.enc | head -n 2

You should see the ASCII text Salted__ followed by 8 random salt bytes. The salt means the same password produces a different key every time.

Compare two derivations of the same password with different salts using openssl kdf:

bash
openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt pass:hunter2 -kdfopt salt:aaaa -kdfopt iter:600000 PBKDF2
openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt pass:hunter2 -kdfopt salt:bbbb -kdfopt iter:600000 PBKDF2

The two outputs are completely different even though the password is identical.

Then time a low and a high iteration count:

bash
time openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt pass:hunter2 -kdfopt salt:aaaa -kdfopt iter:1000 PBKDF2
time openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt pass:hunter2 -kdfopt salt:aaaa -kdfopt iter:2000000 PBKDF2

Record both timings. The gap is the extra work an attacker must repeat for every password guess.

Key points to note:

  • A derived key is only as strong as the password behind it.
  • Salts defeat precomputed tables. Iterations (or memory hardness in scrypt and Argon2) slow down guessing.

Step 3. Asymmetric keys: a public and a private half

An asymmetric key pair has a public key you can share and a private key you must protect. What one does, only the other can undo or verify. Generate three common types:

bash
# RSA 3072
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
# ECDSA on the P-256 curve
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec.key
# Ed25519
openssl genpkey -algorithm ED25519 -out ed.key

Extract the public keys and compare sizes:

bash
for k in rsa ec ed; do openssl pkey -in $k.key -pubout -out $k.pub; done
ls -l *.key *.pub

Inspect the details of each:

bash
openssl pkey -in rsa.key -text -noout | head -n 5
openssl pkey -in ec.key -text -noout | head -n 5
openssl pkey -in ed.key -text -noout | head -n 5

Fill in this table from your own output:

Type Key size Private file size Public file size
RSA 3072 bits
ECDSA P-256 256 bits
Ed25519 256 bits

Note that a 256-bit elliptic curve key gives roughly the security of a 3072-bit RSA key, with far smaller files and faster operations.

Protect a private key with a passphrase:

bash
openssl pkey -in rsa.key -aes256 -out rsa.enc.key
head -n 1 rsa.enc.key

The header should read BEGIN ENCRYPTED PRIVATE KEY. Without the passphrase, a stolen file is much less useful.

Step 4. Using key pairs: encryption and signatures

Public key encryption and digital signatures use the same pair in opposite directions.

Signing proves who wrote something and that it was not changed. The private key signs, the public key verifies:

bash
echo "Deploy build 42" > message.txt
openssl pkeyutl -sign -inkey ed.key -rawin -in message.txt -out message.sig
openssl pkeyutl -verify -pubin -inkey ed.pub -rawin -in message.txt -sigfile message.sig

Expected: Signature Verified Successfully. Now change the message and verify again:

bash
echo "Deploy build 43" > message.txt
openssl pkeyutl -verify -pubin -inkey ed.pub -rawin -in message.txt -sigfile message.sig

Expected: verification fails. This is the basis of code signing, certificates and signed commits.

Encrypting to a recipient uses their public key. RSA can encrypt only small payloads, so real systems encrypt a random symmetric key with RSA and the data with that key (a hybrid scheme):

bash
openssl rand 32 > data.key
openssl pkeyutl -encrypt -pubin -inkey rsa.pub -in data.key -out data.key.enc \
  -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256
openssl pkeyutl -decrypt -inkey rsa.key -in data.key.enc \
  -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 | cmp - data.key && echo "keys match"

This shows the main idea behind TLS, PGP and many other protocols: asymmetric keys protect or agree on a symmetric key, and the symmetric key protects the data.

Step 5. Session keys: agreeing on a secret over an open channel

A session key is a short-lived symmetric key, usually created by a key exchange such as Diffie-Hellman. Simulate two parties, Alice and Bob, with X25519:

bash
openssl genpkey -algorithm X25519 -out alice.key
openssl genpkey -algorithm X25519 -out bob.key
openssl pkey -in alice.key -pubout -out alice.pub
openssl pkey -in bob.key   -pubout -out bob.pub

openssl pkeyutl -derive -inkey alice.key -peerkey bob.pub -out alice.shared
openssl pkeyutl -derive -inkey bob.key   -peerkey alice.pub -out bob.shared
cmp alice.shared bob.shared && echo "same shared secret"
xxd alice.shared

Each side combined its own private key with the other's public key and reached the same 32-byte secret, without that secret ever crossing the network. In real protocols this output goes through a KDF to produce the actual session keys.

Because the keys here were made fresh for this exchange, discarding them afterwards means old traffic cannot be decrypted later. This property is called forward secrecy, and it is why modern TLS uses ephemeral key exchange.

Step 6. SSH keys

SSH uses an asymmetric pair for authentication. Generate an Ed25519 key with a passphrase and a comment:

bash
ssh-keygen -t ed25519 -C "keys-lab" -f ./lab_ssh
ls -l lab_ssh lab_ssh.pub
cat lab_ssh.pub
ssh-keygen -lf lab_ssh.pub

The last command prints the fingerprint, a short hash of the public key used to confirm you are talking to the right key or host.

Compare with an RSA key and a key with no passphrase:

bash
ssh-keygen -t rsa -b 4096 -f ./lab_ssh_rsa -N ""
ssh-keygen -lf lab_ssh_rsa.pub

Check the permissions. SSH refuses to use a private key that others can read:

bash
stat -c '%a %n' lab_ssh lab_ssh_rsa
chmod 644 lab_ssh
ssh-keygen -y -f lab_ssh
chmod 600 lab_ssh

Record what happens when permissions are too open.

Step 7. PGP keys

PGP keys bundle several keys: a primary key for certifying, and subkeys for signing, encryption and authentication. Use a temporary keyring so your real one is untouched:

bash
export GNUPGHOME=$(mktemp -d)
chmod 700 $GNUPGHOME
gpg --batch --passphrase '' --quick-generate-key "Lab User <lab@example.invalid>" ed25519 cert 1y
gpg --list-keys --keyid-format long

Add subkeys and list them:

bash
FPR=$(gpg --list-keys --with-colons | awk -F: '/^fpr/ {print $10; exit}')
gpg --batch --passphrase '' --quick-add-key $FPR ed25519 sign 6m
gpg --batch --passphrase '' --quick-add-key $FPR cv25519 encr 6m
gpg --list-keys --with-subkey-fingerprints

Note the usage flags: C certify, S sign, E encrypt. Subkeys can expire or be replaced without replacing your identity. Create a revocation certificate now, the way you should before any real key is used:

bash
gpg --batch --yes --output revoke.asc --gen-revoke $FPR

Look at the header of revoke.asc. This file lets you tell others a key can no longer be trusted, even if you lose access to it.

Step 8. Key storage, rotation and clean-up

Check where your keys are and who can read them:

bash
find ~/keys-lab -type f \( -name "*.key" -o -name "lab_ssh*" \) -exec stat -c '%a %U %n' {} \;

Tighten permissions on every private key:

bash
chmod 600 ~/keys-lab/*.key ~/keys-lab/lab_ssh ~/keys-lab/lab_ssh_rsa

Simulate a rotation: generate a new Ed25519 pair, re-sign the message, and confirm the old public key no longer verifies the new signature.

bash
openssl genpkey -algorithm ED25519 -out ed2.key
openssl pkey -in ed2.key -pubout -out ed2.pub
echo "Deploy build 44" > message.txt
openssl pkeyutl -sign -inkey ed2.key -rawin -in message.txt -out message2.sig
openssl pkeyutl -verify -pubin -inkey ed.pub  -rawin -in message.txt -sigfile message2.sig
openssl pkeyutl -verify -pubin -inkey ed2.pub -rawin -in message.txt -sigfile message2.sig

The first check should fail and the second succeed. Anyone who trusts the old public key needs to be told about the new one, which is why rotation needs a distribution plan and not only a new file.

Finally, clean up:

bash
cd ~ && rm -rf ~/keys-lab
rm -rf "$GNUPGHOME"; unset GNUPGHOME

Findings

Complete this section with your own results. Use the points below as a guide.

Key type Purpose Shared with others? Typical size Main risk
Symmetric (AES-256) Bulk encryption Both parties, secretly 256 bits Distribution and reuse
Derived (PBKDF2) Turn a password into a key No 256 bits output Weak password, low iterations
RSA pair Signatures, key transport Public half only 3072 bits or more Slow, large, poor padding choices
ECDSA / Ed25519 pair Signatures, SSH, TLS Public half only 256 bits Private key theft, bad randomness
X25519 session key Key agreement Public halves only 256 bits Missing authentication of the peer
SSH key Authentication Public half in authorized_keys 256 to 4096 bits Unprotected private key
PGP key and subkeys Email, signing, identity Public key and fingerprint Varies Lost key without a revocation certificate

Things to confirm from your run:

  • The altered AES key failed to decrypt (note the exact error).
  • Two salts gave two different derived keys, and the high iteration count took noticeably longer (add your timings).
  • File sizes for RSA, ECDSA and Ed25519 keys (fill in the table in Step 3).
  • Signature verification passed for the original message and failed after it was edited.
  • Both sides of the X25519 exchange produced identical secrets.
  • The old public key failed to verify signatures made after rotation.

Lessons learned

  • "A key" means very different things. Always ask what it is for, who holds it, and how long it lives.
  • Symmetric keys are fast but have a distribution problem. Asymmetric keys solve distribution but are slower, so real systems combine them.
  • Password-derived keys are limited by password quality. Salts and slow KDFs raise the cost of guessing but cannot rescue a weak password.
  • Prefer modern algorithms: Ed25519 or P-256 for signatures, X25519 for key exchange, AES-GCM or ChaCha20-Poly1305 for data, and RSA of at least 3072 bits where RSA is needed.
  • Short-lived session keys limit damage: stealing a long-term key should not unlock past traffic.
  • Protect private keys with passphrases and tight file permissions, keep them away from the data they protect, and never share them.
  • Plan for the end of a key's life from the start: expiry dates, rotation, and a revocation certificate created in advance.

References

  • NIST SP 800-57 Part 1, Recommendation for Key Management
  • NIST SP 800-132, Recommendation for Password-Based Key Derivation
  • RFC 8032, Edwards-Curve Digital Signature Algorithm (EdDSA)
  • RFC 7748, Elliptic Curves for Security (X25519)
  • RFC 8018, PKCS #5: Password-Based Cryptography Specification
  • OWASP Cryptographic Storage Cheat Sheet
  • OpenSSH manual pages: ssh-keygen(1)
  • GnuPG documentation: https://gnupg.org/documentation/