Encryption
A clear guide to encryption, covering plaintext and ciphertext, Kerckhoffs's principle, Shannon's confusion and diffusion, and protecting data at rest, in transit, and in use.
Imagine you need to send an important confidential letter to a friend across town. If you write the letter on a postcard and give it to a messenger, anyone along the route can read it: the messenger, curious bystanders, or someone who intercepts the delivery. Now imagine that before handing over the letter, you run the text through a secret mathematical code using a unique key. The words turn into an unreadable string of scrambled characters. If someone intercepts the postcard now, all they see is random gibberish. Only your friend, who holds the matching key, can unscramble the characters and read the original message. That is encryption. Encryption is the process of converting readable information (called plaintext) into an unreadable, scrambled format (called ciphertext). Even if an attacker taps your network cables or steals your storage drives, your confidential information stays protected because they cannot read it without the key.
Definition
Encryption is the cryptographic process of transforming readable information (plaintext) into an unreadable format (ciphertext) using a mathematical algorithm (cipher) and a secret key. The original information can only be recovered through decryption by someone who possesses the corresponding cryptographic key.
Why It Matters
In our interconnected world, data travels constantly across public Wi-Fi networks, cellular towers, internet routers, and shared cloud servers. You cannot rely on physical security alone to keep your data safe. Cables can be tapped, network traffic can be monitored, and laptops can be lost or stolen. Encryption provides the core foundation of digital confidentiality. It ensures that only authorized people can read private communications, financial records, and medical files. Modern data privacy laws, such as GDPR and HIPAA, recognize this importance: if a lost corporate laptop has an encrypted hard drive, it is generally not treated as a public data breach because the data remains completely unreadable to whoever finds it.
How It Works
Modern encryption relies on foundational mathematical principles established by cryptographers like Auguste Kerckhoffs and Claude Shannon: 1. Kerckhoffs's Principle (The Golden Rule of Cryptography): In 1883, Auguste Kerckhoffs stated that a cryptosystem must remain secure even if everything about the system is public knowledge, as long as the key remains secret. • Never rely on secret, proprietary algorithms (an approach known as 'security through obscurity'). The most trusted algorithms in the world, such as AES-256 and ChaCha20, publish their complete mathematical designs openly so thousands of researchers can test them for flaws. Security comes entirely from the secrecy and randomness of the key, not from hiding how the lock works. 2. Shannon's Core Properties: Confusion and Diffusion: • Confusion: Makes the relationship between the key and the ciphertext as complex and tangled as possible. Changing a single bit of the key should change the ciphertext in an unpredictable way. • Diffusion: Spreads the influence of each plaintext character across the entire ciphertext. If you change a single letter in your original message, about half of the bits in the scrambled output should flip randomly, hiding any visible patterns. 3. The Three States of Data: • Data in Transit: Information traveling across networks (like browsing a website or making an API call). Protected by protocols such as TLS 1.3, IPsec, and WireGuard VPNs. • Data at Rest: Information stored on solid-state drives, databases, and backup media. Protected by algorithms like AES-256, alongside disk encryption tools such as BitLocker and LUKS. • Data in Use: Information actively loaded into system RAM and CPU registers while programs run. Historically vulnerable to memory extraction, this state is now defended by hardware enclaves (Confidential Computing technologies like Intel SGX and AMD SEV). 4. Symmetric vs Asymmetric Approaches: • Symmetric Encryption: Uses one shared secret key for both scrambling and unscrambling (for example, AES-256-GCM). It is fast and handles large volumes of data smoothly. • Asymmetric Encryption: Uses a mathematically linked pair of keys, a public key to encrypt and a private key to decrypt (such as RSA and ECC Curve25519). This neatly solves the problem of sharing keys over an untrusted network.
The Encryption and Decryption Pipeline
Key Points
- Encryption converts readable Plaintext into scrambled Ciphertext; Decryption reverses that process using a key.
- Kerckhoffs's Principle: System security depends strictly on keeping the key secret, never on keeping the algorithm hidden.
- Confusion obscures the connection between key and ciphertext; Diffusion spreads plaintext patterns across the ciphertext.
- Data must be protected across three distinct states: at rest, in transit, and in use.
- AES-256-GCM is the modern global industry standard for fast, authenticated bulk data encryption.
Steps
Classify Data and Identify Risks
Inventory and categorize information by sensitivity, such as personally identifiable information (PII), payment details, authentication tokens, and business records.
Adopt Modern Authenticated Ciphers
Use Authenticated Encryption with Associated Data (AEAD) ciphers like AES-256-GCM or ChaCha20-Poly1305. Avoid outdated, unauthenticated modes like plain CBC or ECB.
Protect Keys with a KMS or HSM
Never hardcode cryptographic keys in application source code. Store root keys in dedicated Hardware Security Modules (HSMs) or cloud Key Management Services (KMS) with strict access policies.
Enforce TLS 1.3 for Data in Transit
Disable unencrypted HTTP and deprecated TLS versions. Require TLS 1.3 for all public web traffic and internal communication between microservices.
Enable Disk Encryption for Data at Rest
Turn on full-disk encryption (BitLocker, FileVault, or dm-crypt/LUKS) for laptops and servers, and use database column-level encryption for sensitive user records.
Examples
The Caesar Cipher vs Modern Cryptography
Julius Caesar protected military messages by shifting the alphabet by three places: 'A' became 'D', 'B' became 'E', and so on. A computer today can break this Caesar cipher in microseconds because there are only 25 possible shifts to check. However, the basic idea remains the same: the shift number is the Key, and the rule for substituting letters is the Cipher. Modern ciphers use enormous mathematical keys with so many possibilities that checking them all is practically impossible.
Real-World Examples
WhatsApp End-to-End Encryption (Signal Protocol)
WhatsApp protects messages for over two billion users using the open-source Signal Protocol. Messages are encrypted on your phone using AES-256-GCM and keys negotiated through the Double Ratchet Algorithm with Curve25519. Because the private keys live only on the sender's and receiver's personal devices, neither WhatsApp's parent company Meta, cellular network providers, nor eavesdroppers on the internet can read your messages.
Technical Examples
import crypto from "crypto";
// Authenticated Encryption with Associated Data (AEAD)
const ALGORITHM = "aes-256-gcm";
const KEY_LENGTH_BYTES = 32; // 256-bit key
const IV_LENGTH_BYTES = 12; // 96-bit Initialization Vector (Standard for GCM)
interface EncryptedPayload {
ciphertext: string;
iv: string;
authTag: string;
}
/**
* Encrypts plaintext using AES-256-GCM and creates a tamper-evident authentication tag
*/
export function encrypt(plaintext: string, secretKey: Buffer): EncryptedPayload {
// Generate a cryptographically secure, fresh IV for every encryption call
const iv = crypto.randomBytes(IV_LENGTH_BYTES);
const cipher = crypto.createCipheriv(ALGORITHM, secretKey, iv);
let ciphertext = cipher.update(plaintext, "utf8", "hex");
ciphertext += cipher.final("hex");
// Retrieve the 16-byte authentication tag (verifies that data has not been modified)
const authTag = cipher.getAuthTag().toString("hex");
return {
ciphertext,
iv: iv.toString("hex"),
authTag,
};
}
/**
* Decrypts ciphertext and verifies the authentication tag
*/
export function decrypt(payload: EncryptedPayload, secretKey: Buffer): string {
const decipher = crypto.createDecipheriv(
ALGORITHM,
secretKey,
Buffer.from(payload.iv, "hex")
);
// Set the expected authentication tag before completing decryption
decipher.setAuthTag(Buffer.from(payload.authTag, "hex"));
let decrypted = decipher.update(payload.ciphertext, "hex", "utf8");
// If the ciphertext or tag was altered in any way, final() throws an error!
decrypted += decipher.final("utf8");
return decrypted;
}Encryption vs Encoding (e.g., Base64)
| Aspect | Encryption | Encoding (e.g., Base64) |
|---|---|---|
| Primary Objective | Confidentiality and secrecy (protecting data from unauthorized eyes) | Data compatibility (converting binary bytes into safe text characters) |
| Key Requirement | Required: impossible to reverse without the secret cryptographic key | None: anyone can decode it instantly without a key or password |
| Security Level | Mathematically secure against brute-force attacks | Zero security: provides no confidentiality whatsoever |
| Common Examples | AES-256-GCM, ChaCha20, RSA-4096 | Base64, ASCII hex, URL-encoding |
Shannon's Information Theory & The One-Time Pad
Advantages
- Strong Confidentiality: Properly configured AES-256 cannot be cracked by modern computing hardware.
- Regulatory Protection: Lost or stolen encrypted devices generally do not trigger public data breach penalties under laws like GDPR and HIPAA.
- Safe Cloud Storage: Organizations can safely host data in multi-tenant cloud storage without exposing contents to the cloud provider.
Limitations
- Risk of Permanent Key Loss: If you lose the decryption key, the encrypted data cannot be recovered.
- Processing Overhead: Encrypting and decrypting vast amounts of high-speed data requires processing cycles, though modern CPU instructions (AES-NI) minimize this impact.
Interview Questions
Explain Kerckhoffs's Principle and why 'Security through Obscurity' fails in cryptography.
Kerckhoffs's Principle states that a cryptosystem must be secure even if everything about the design is publicly known, as long as the key is kept secret. Secret, proprietary algorithms fail because they eventually leak through reverse engineering, software bugs, or insider leaks. Once a hidden algorithm is exposed, every piece of data encrypted with it is at risk. By contrast, open standard algorithms like AES are publicly reviewed by mathematicians around the world for years, ensuring that finding a flaw is exceptionally difficult and that endpoint security depends only on keeping individual keys safe.
What is Confidential Computing and how does it protect data in use?
Confidential Computing protects data while it is actively being processed in memory. It uses hardware-isolated Trusted Execution Environments (TEEs) or enclaves, such as Intel SGX or AMD SEV. Memory allocated to these enclaves is automatically encrypted by the CPU hardware. Even if an attacker gains root access to the operating system or hypervisor, they cannot read or tamper with the unencrypted data inside the enclave.
Practice Questions
- Encode a string in Base64 using your terminal (for example, echo 'MySecret' | base64) and decode it. Notice why Base64 provides formatting compatibility rather than security.
- Turn on disk encryption on a test drive (BitLocker on Windows, FileVault on macOS, or LUKS on Linux) and make sure you understand how recovery keys work.
