Cryptography Guide

A complete reference from classical ciphers to modern cryptographic systems

What is Cryptography?

Cryptography is the science and art of securing information by transforming it into an unreadable format for unauthorized parties. From ancient scrolls to HTTPS, it underlies all digital trust.

Confidentiality

Only intended recipients can read the data. Achieved through encryption algorithms like AES or RSA.

Integrity

Data has not been altered in transit. Achieved through hash functions and MACs (Message Authentication Codes).

Authentication

Verifying the identity of a sender or receiver. Achieved via digital signatures and certificates.

Non-repudiation

A sender cannot deny having sent a message. Achieved through digital signatures tied to private keys.

Core terminology

TermDefinition
PlaintextOriginal readable data before encryption
CiphertextScrambled, unreadable output after encryption
KeySecret value that controls encryption/decryption
CipherThe algorithm used to encrypt and decrypt
KeyspaceTotal number of possible key values
EntropyMeasure of randomness / unpredictability in a key

A Brief History

~1900 BCE
Ancient Egyptians used substitution hieroglyphs to obscure meaning in tomb inscriptions.
~100 BCE
Julius Caesar uses the Caesar cipher — a simple rotation cipher to encrypt military dispatches (ROT-3).
1466
Leon Alberti invents the polyalphabetic cipher, using multiple substitution alphabets to resist frequency analysis.
1917
The Zimmermann Telegram — a coded German diplomatic message — is broken by British intelligence, influencing WWI's outcome.
1940s
Alan Turing and team crack the Enigma machine at Bletchley Park, a watershed moment in both cryptanalysis and computing.
1976
Diffie and Hellman publish "New Directions in Cryptography", introducing public-key cryptography — the most important cryptographic innovation of the 20th century.
1977
RSA algorithm published by Rivest, Shamir, and Adleman. DES adopted as the US federal standard for symmetric encryption.
2001
AES (Advanced Encryption Standard) adopted by NIST, replacing DES with a stronger, faster block cipher.
2022+
NIST begins standardizing post-quantum cryptographic algorithms (CRYSTALS-Kyber, CRYSTALS-Dilithium) to resist quantum computing threats.

Symmetric Encryption

Symmetric encryption uses a single shared key for both encryption and decryption. It is fast and suitable for bulk data, but key distribution is a challenge.

Plaintext
🔑 Encrypt (Key)
Ciphertext
🔑 Decrypt (Same Key)
Plaintext

Block ciphers

Encrypt fixed-size blocks of data (e.g., 128 bits). The same key is applied to each block using a specific mode of operation.

Modern
AES
Advanced Encryption Standard. Block size 128 bits, key sizes 128/192/256 bits. Gold standard of symmetric encryption, used in TLS, WPA2, disk encryption.
Since 2001
Legacy
DES
Data Encryption Standard. 64-bit blocks, 56-bit key. Replaced by AES. Now insecure — brute-forceable in hours.
1977–2001
Legacy
3DES
Triple DES. Applies DES three times with 112-bit effective security. Deprecated by NIST in 2019.
~1998
Modern
Blowfish
64-bit block, key sizes 32–448 bits. Fast and patent-free. Common in older password hashing (bcrypt's cipher).
1993

Stream ciphers

Encrypt data one bit or byte at a time using a pseudo-random keystream XOR'd with plaintext. Faster than block ciphers for continuous data.

Modern
ChaCha20
256-bit stream cipher designed by DJB. Used in TLS 1.3, WireGuard. Resistant to timing attacks, software-efficient.
2008
Broken
RC4
Once widely used in SSL and WEP. Multiple statistical biases discovered. Do not use.
Deprecated

Modes of operation (for block ciphers)

ModeFull NameNotes
ECBElectronic Codebook❌ Deterministic — identical blocks → identical ciphertext. Never use.
CBCCipher Block ChainingEach block XOR'd with previous ciphertext. Requires IV. Vulnerable to padding oracle attacks.
CTRCounter ModeConverts block cipher to stream cipher. Parallelizable. Requires unique nonce.
GCMGalois/Counter Mode✅ Recommended. Authenticated encryption (AEAD). Provides confidentiality + integrity.
CCMCounter with CBC-MACAEAD mode used in IEEE 802.11 (WPA2). Good for constrained devices.

Best practice: Always use AES-256-GCM. It provides authenticated encryption, meaning you get both confidentiality and integrity protection in a single primitive.

Asymmetric (Public-Key) Encryption

Uses a mathematically linked key pair: a public key (share freely) and a private key (keep secret). What one key encrypts, only the other can decrypt.

Public Key

  • Freely distributed
  • Used to encrypt messages for you
  • Used to verify your signatures
  • Cannot decrypt or sign

Private Key

  • Never shared
  • Used to decrypt messages
  • Used to create digital signatures
  • Mathematically derived from keygen

Key algorithms

Asym
RSA
Based on difficulty of factoring large integers. Keys: 2048–4096 bits. Used for key exchange, signatures, TLS certificates. Slow for bulk data.
1977
Asym
ECC
Elliptic Curve Cryptography. Smaller keys (256 bits ≈ RSA 3072 bits) with equivalent security. Basis for ECDSA and ECDH.
1985
Asym
DSA / ECDSA
Digital Signature Algorithm / Elliptic Curve DSA. Used for digital signatures, SSH keys, code signing, TLS. ECDSA is preferred.
1991
Modern
Ed25519
Edwards-curve variant, very fast and secure. No weak random number vulnerability like ECDSA. Preferred for SSH and modern TLS.
2011
Modern
X25519
Curve25519-based Diffie-Hellman key exchange. Used in TLS 1.3, Signal protocol, WireGuard.
2006

Diffie-Hellman key exchange

Allows two parties to establish a shared secret over an insecure channel without ever transmitting the secret itself.

Alice & Bob agree on public params (g, p)
Alice picks secret a, sends g^a mod p
Bob picks secret b, sends g^b mod p
Shared secret: (g^b)^a mod p = (g^a)^b mod p

Digital signatures

Message
Hash(msg)
Sign(private key)
Signature

Verification: anyone with your public key can run Verify(signature, public key) → outputs valid or invalid.

RSA with keys under 2048 bits is considered weak. For new systems, prefer ECC (P-256 or X25519). RSA-1024 can be factored with enough compute.

Cryptographic Hash Functions

A hash function maps arbitrary-length input to a fixed-length output (digest). It is a one-way function — easy to compute, computationally infeasible to reverse.

Deterministic

Same input always produces the same hash output. No randomness involved.

Avalanche Effect

Changing even one bit of input completely changes the output — unpredictably.

Collision Resistant

Practically impossible to find two different inputs that produce the same hash.

Pre-image Resistant

Given a hash output, it's infeasible to find the original input.

Common hash algorithms

AlgorithmOutputStatusUse case
MD5128 bitsBrokenChecksums only — collisions trivially found
SHA-1160 bitsDeprecatedLegacy — SHAttered attack broke it in 2017
SHA-256256 bitsSecureTLS, code signing, Bitcoin, general purpose
SHA-512512 bitsSecureHigher security, slower on 32-bit systems
SHA-3 / Keccak224–512 bitsSecureNIST standard, different design from SHA-2
BLAKE3variableModernFastest secure hash. Used in Bao, IPFS

Password hashing (key derivation)

Regular hashes are too fast for passwords — attackers can hash millions of guesses per second. Password hashing functions are deliberately slow and memory-hard.

Best
Argon2id
Winner of the Password Hashing Competition (2015). Memory-hard, CPU-hard, resistant to GPU and ASIC attacks. Use this for new systems.
2015
Good
bcrypt
Based on Blowfish. Cost factor is adjustable. Widely supported. Capped at 72 bytes input.
1999
Good
scrypt
Memory-hard function used in Litecoin, some password managers. Parameter tuning required.
2009
Good
PBKDF2
NIST-approved, FIPS-compliant. Not memory-hard, but widely available and sufficient with high iterations (600k+ for HMAC-SHA256).
2000

HMAC (Hash-based Message Authentication Code)

Combines a cryptographic hash with a secret key to verify both the integrity and authenticity of a message.

// HMAC-SHA256 construction
HMAC(key, message) = Hash((key ⊕ opad) || Hash((key ⊕ ipad) || message))

// Used in: JWT tokens, TLS MAC, API authentication headers
Authorization: HMAC-SHA256 timestamp=1234&nonce=abc&sig=e3b0c442...

Cryptographic Protocols

TLS / SSL — Transport Layer Security

The protocol that secures HTTPS. It uses asymmetric crypto for key exchange and authentication, then symmetric crypto for the bulk data transfer.

Step 1
Client Hello (supported ciphers, random)
Step 2
Server Hello + Certificate (public key)
Step 3
Key Exchange (ECDHE / X25519)
Step 4
Derive session keys from shared secret
Step 5
Encrypted data transfer (AES-256-GCM)

TLS 1.3 (2018) simplified the handshake, removed weak ciphers (RC4, DES, SHA-1), and requires forward secrecy. Always use TLS 1.2 minimum, prefer 1.3.

PKI — Public Key Infrastructure

Certificate Authorities (CA)

Trusted third parties (DigiCert, Let's Encrypt, etc.) that sign X.509 certificates, binding a public key to an identity.

X.509 Certificates

Standard format containing: subject name, public key, issuer, validity period, and the CA's digital signature.

Certificate Chain

End-entity cert → Intermediate CA → Root CA. Root CAs are pre-installed in OSes and browsers as trust anchors.

Certificate Revocation

CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) handle invalidating compromised certs.

Other important protocols

PGP / GPG
Pretty Good Privacy. Web-of-trust model. Used for email encryption and file signing. Combines RSA/ECC with AES for hybrid encryption.
1991
SSH
Secure Shell. Authenticated remote access using asymmetric keys (Ed25519/RSA) and symmetric session encryption. Standard for server administration.
1995
Signal Protocol
Double Ratchet + X3DH. Provides end-to-end encryption with forward secrecy and break-in recovery. Used in Signal, WhatsApp, Wire.
2013
WireGuard
Modern VPN protocol. Uses ChaCha20-Poly1305, Curve25519, BLAKE2s. Minimal codebase (~4000 LOC), replaces OpenVPN/IPsec.
2017

Common Attacks

Brute Force

Trying every possible key until the correct one is found. Defended against with large key sizes (128+ bits).

Dictionary Attack

Using pre-computed wordlists against password hashes. Defeated by salting and slow hash functions.

Rainbow Table

Precomputed hash → password mappings. A unique, random salt per password renders rainbow tables useless.

Man-in-the-Middle

Intercepting communication between two parties. Defeated by certificate pinning and authenticated key exchange.

Replay Attack

Reusing captured valid messages. Defeated by nonces, timestamps, and session tokens.

Side-Channel

Exploiting physical information (timing, power, EM emissions) rather than mathematical weaknesses. Difficult to fully prevent.

Padding Oracle

Exploiting error messages from block cipher padding to decrypt data. Defeated by authenticated encryption (AEAD like GCM).

Birthday Attack

Finding hash collisions using probability theory (~2^n/2 operations). Reason SHA-1 (160-bit) is broken — practical collision found.

Quantum computing threats

Shor's Algorithm can break RSA and ECC by efficiently factoring large numbers and computing discrete logs on a sufficiently powerful quantum computer. This is not imminent but drives post-quantum cryptography research. NIST has standardized Kyber (key encapsulation) and Dilithium (signatures) as PQC replacements.

Grover's Algorithm speeds up symmetric key searching, reducing AES-128 to ~2^64 effective security. Use AES-256 as a precaution against future quantum attacks.

Interactive Playground

Caesar Cipher

Khoor Zruog

Vigenère Cipher

XOR Cipher (hex output)

SHA-256 Hash (via SubtleCrypto)

a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

Base64 Encoding / Decoding

Best Practices & Recommendations

Encryption

Symmetric

  • Use AES-256-GCM for new code
  • Never reuse nonces
  • Avoid ECB mode entirely
  • Use AEAD ciphers only
Asymmetric

Public Key

  • RSA: minimum 2048 bits
  • Prefer Ed25519 / X25519
  • Rotate keys periodically
  • Store private keys in HSMs
Hashing

Hashing & MACs

  • SHA-256 minimum for general use
  • Argon2id for passwords
  • Always salt password hashes
  • HMAC-SHA256 for message auth
Transport

Protocols

  • TLS 1.3 preferred, 1.2 minimum
  • Enable HSTS headers
  • Certificate pinning for mobile
  • Disable SSLv3, TLS 1.0/1.1

Things to never do

Never roll your own cryptography. Use well-audited libraries: libsodium, OpenSSL, Web Crypto API, BouncyCastle. Custom crypto is almost always broken in subtle ways.

Never use MD5 or SHA-1 for security-sensitive operations. Never use DES, 3DES, or RC4. Never use RSA with PKCS#1 v1.5 padding (use OAEP).

Never hardcode keys, passwords, or secrets in source code or version control. Use environment variables, secrets managers, or HSMs.

Recommended libraries by language

LanguageLibraryNotes
Pythoncryptography, PyNaClUse cryptography package, not pycrypto
JavaScriptWeb Crypto API, libsodium.jsAvoid CryptoJS for new projects
Java / KotlinBouncyCastle, JDK javax.cryptoUse JCA providers correctly
Gocrypto/ stdlibExcellent standard library coverage
Rustring, RustCryptoring wraps BoringSSL primitives
C / C++libsodium, OpenSSLlibsodium has safer default API