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
| Term | Definition |
|---|---|
Plaintext | Original readable data before encryption |
Ciphertext | Scrambled, unreadable output after encryption |
Key | Secret value that controls encryption/decryption |
Cipher | The algorithm used to encrypt and decrypt |
Keyspace | Total number of possible key values |
Entropy | Measure of randomness / unpredictability in a key |
A Brief History
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.
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.
AES
DES
3DES
Blowfish
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.
ChaCha20
RC4
Modes of operation (for block ciphers)
| Mode | Full Name | Notes |
|---|---|---|
ECB | Electronic Codebook | ❌ Deterministic — identical blocks → identical ciphertext. Never use. |
CBC | Cipher Block Chaining | Each block XOR'd with previous ciphertext. Requires IV. Vulnerable to padding oracle attacks. |
CTR | Counter Mode | Converts block cipher to stream cipher. Parallelizable. Requires unique nonce. |
GCM | Galois/Counter Mode | ✅ Recommended. Authenticated encryption (AEAD). Provides confidentiality + integrity. |
CCM | Counter with CBC-MAC | AEAD 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
RSA
ECC
DSA / ECDSA
Ed25519
X25519
Diffie-Hellman key exchange
Allows two parties to establish a shared secret over an insecure channel without ever transmitting the secret itself.
a, sends g^a mod pb, sends g^b mod p(g^b)^a mod p = (g^a)^b mod pDigital signatures
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
| Algorithm | Output | Status | Use case |
|---|---|---|---|
MD5 | 128 bits | Broken | Checksums only — collisions trivially found |
SHA-1 | 160 bits | Deprecated | Legacy — SHAttered attack broke it in 2017 |
SHA-256 | 256 bits | Secure | TLS, code signing, Bitcoin, general purpose |
SHA-512 | 512 bits | Secure | Higher security, slower on 32-bit systems |
SHA-3 / Keccak | 224–512 bits | Secure | NIST standard, different design from SHA-2 |
BLAKE3 | variable | Modern | Fastest 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.
Argon2id
bcrypt
scrypt
PBKDF2
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.
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
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
Vigenère Cipher
XOR Cipher (hex output)
SHA-256 Hash (via SubtleCrypto)
Base64 Encoding / Decoding
Best Practices & Recommendations
Symmetric
- Use AES-256-GCM for new code
- Never reuse nonces
- Avoid ECB mode entirely
- Use AEAD ciphers only
Public Key
- RSA: minimum 2048 bits
- Prefer Ed25519 / X25519
- Rotate keys periodically
- Store private keys in HSMs
Hashing & MACs
- SHA-256 minimum for general use
- Argon2id for passwords
- Always salt password hashes
- HMAC-SHA256 for message auth
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
| Language | Library | Notes |
|---|---|---|
| Python | cryptography, PyNaCl | Use cryptography package, not pycrypto |
| JavaScript | Web Crypto API, libsodium.js | Avoid CryptoJS for new projects |
| Java / Kotlin | BouncyCastle, JDK javax.crypto | Use JCA providers correctly |
| Go | crypto/ stdlib | Excellent standard library coverage |
| Rust | ring, RustCrypto | ring wraps BoringSSL primitives |
| C / C++ | libsodium, OpenSSL | libsodium has safer default API |