Introduction
Cryptography is everywhere — and yet most of us treat it like magic.
From encrypted chats and online banking to firmware updates on satellites, the systems we rely on daily are secured (or compromised) by cryptography. And too often, it fails — not because the math was wrong, but because the implementation was.
This book exists to change that.
You’re not here to memorize equations. You’re here to understand, implement, and apply cryptographic primitives to real-world systems using a language designed to prevent mistakes before they happen: Rust.
Whether you’re building infrastructure, smart contracts, embedded firmware, or secure APIs, this book gives you the tools to use cryptography safely, idiomatically, and fearlessly — one primitive, one project, one domain at a time.
Who This Book Is For
- Rust developers who want to understand and apply cryptography
- Security engineers transitioning to Rust
- Curious hackers tired of black-box crypto
- Systems developers who care about safety, correctness, and resilience
What You’ll Learn
- The foundations and mental models behind symmetric and asymmetric cryptography
- How to use modern cryptographic crates in Rust safely and idiomatically
- Where cryptographic primitives show up in real-world domains (blockchain, embedded, medical, etc.)
- How to design, test, and publish your own secure Rust crypto crate
What This Book Is Not
- ❌ A math-heavy cryptography textbook
- ❌ A copy-paste cookbook
- ❌ A blockchain hype manual
We won’t drown you in proofs, but we’ll explain just enough math to build intuition. We’ll write real code — not just use libraries. And we’ll focus on systems-level crypto, not speculative tokens.
What You’ll Need
- ✅ Basic experience with Rust (enough to build a CLI or follow
cargo run
) - ✅ Comfort with reading code, refactoring, and using crates
- ✅ Curiosity, and a bias toward safe, practical, applied learning
Let’s begin
This book won’t make you a cryptographer in the academic sense — but it will make you something just as rare and valuable: A Rust engineer who understands, wields, and applies cryptography with precision, context, and confidence.
You won’t just read — you’ll build.
Focused implementations and applied examples are available here and updated weekly.
How to Use This Book
This book is designed to be practical, modular, and domain-focused.
You can read it front to back, or jump directly to the domains and primitives most relevant to your work.
Structure
The book is organized into four major parts:
Foundations — Why Rust is uniquely suited for secure cryptographic engineering
Primitives — The core building blocks of cryptography, with Rust-focused usage and implementation
Applied Domains — Real-world systems and how they use cryptography in practice (blockchain, defense, aerospace, medical, infrastructure, etc.)
Crate Building — How to architect, test, audit, and publish your own cryptographic crate in Rust
Each chapter includes:
- Plain-language explanations
- Rust code examples using community crates
- Security insights and common pitfalls
- Domain-specific applications
Code and Examples
Most chapters include runnable Rust code to illustrate key concepts.
- You’ll need a working Rust toolchain (
rustup
,cargo
) - Code examples are written for Rust 2021 edition
Each folder in that repo corresponds to a chapter or concept from the book.
You can clone it, run the examples, and experiment freely without touching production code or complex crates.
Note: These examples are minimal and didactic. They are not full cryptographic libraries.
Where to Find the Code
New! Want hands-on exercises for each chapter?
Check out the companion repository: sealed-in-rust-book-code repo
Non-linear Reading
This book doesn’t assume linear progress.
- Want to build a secure file encryption tool? Symmetric Ciphers + Secure Infrastructure
- Curious about smart contracts? Go directly to ECC and Blockchain & Web3
- Working on embedded firmware? Check out Ascon, PRESENT, and Defense & Aerospace
Each domain chapter reminds you of the necessary primitives — like a map, not a locked path.
Contributing, Feedback, & Issues
This book is a living project.
- Errors? Open an issue or PR on the GitHub repo
- Suggestions? You’re welcome to share ideas for domains, examples, or improvements
- Contributions to the examples repo are also welcome
Final Note
This is not a cryptography textbook — it’s a cryptographic engineering manual.
By the end, you’ll not only understand the primitives, you’ll know how to use them to secure real systems — in Rust, by design, not by accident.
Let’s begin.
Cryptography is a Systems Problem
Cryptography isn’t just about math.
Yes, it starts with elegant algebra and deep number theory — but where it breaks is almost always in the system. Real-world failures come from poor implementations, leaky abstractions, memory bugs, side channels, or simply misunderstanding what problem crypto is supposed to solve.
It’s easy to misuse even “secure” primitives. AES1 in ECB mode2 is fast — and useless. RSA3 without padding4 is a gift to attackers. And a perfectly strong key means nothing if it’s printed to your logs.
This is why cryptography is a systems engineering problem first.
And it’s why Rust matters.
Rust doesn’t make crypto correct by default — nothing does — but it gives you tools to avoid entire classes of catastrophic bugs.
Memory safety, explicit ownership, fearless concurrency, and tight control over the machine — these aren’t “nice to have.” They’re security features.
In this book, we’ll treat crypto not as a black box, but as a series of concrete systems problems — and show how Rust lets us solve them with clarity and precision.
-
AES (Advanced Encryption Standard) is a widely used symmetric cipher known for its performance and strong security — when used correctly. ↩
-
ECB (Electronic Code Book) mode encrypts each block independently, revealing patterns in the plaintext and making it insecure for most purposes. ↩
-
RSA (Rivest–Shamir–Adleman) is a public-key cryptosystem used for encryption and digital signatures. It relies on the difficulty of factoring large integers. ↩
-
Padding in RSA adds randomness or structure to the plaintext before encryption, preventing deterministic outputs. Without it, attackers can guess messages, detect patterns, or exploit mathematical properties to break the cipher. ↩
Safety, Performance, Predictability
Rust is often praised for its speed and memory safety, but in the world of cryptographic engineering, these traits aren’t just nice-to-haves — they’re critical.
Safety
Bugs in cryptographic code can be catastrophic. Memory corruption, undefined behavior, or uninitialized values can leak secrets or open attack vectors. Rust eliminates entire classes of these bugs at compile time:
- No nulls
- No uninitialized memory
- No data races
- No buffer overflows
This safety isn’t enforced by a runtime, but by the borrow checker at compile time. That makes Rust extremely attractive for writing low-level cryptographic code without sacrificing control.
️Performance
Rust compiles to fast native code, comparable to C and C++. There’s no garbage collector, and you pay only for what you use. This matters because cryptography is often used in:
- Performance-critical code paths (e.g. TLS handshakes, file encryption)
- Embedded systems where CPU cycles and memory are limited
Rust lets you stay close to the metal while writing high-level abstractions — it’s a rare balance.
Predictability
In cryptography, predictable behavior is essential. You need fine-grained control over:
- Timing — Avoid accidental leaks via early-exit comparisons or branching on secrets
- Memory — Prevent unexpected reallocations or optimization side effects
- Execution — Ensure constant-time logic without interference from JITs or hidden runtime behavior
Rust gives you this control by default, making it a strong ally in defending against side-channel attacks.
In short: Rust brings the low-level control of C, the safety of functional languages, and the clarity of modern syntax — all in a single toolchain. That’s why cryptographers and security engineers are increasingly turning to it.
The Cost of Unsafety in Crypto: Famous Failures
Cryptography doesn’t fail because math is broken — it fails because systems leak, code panics, or side-channels whisper secrets.
And most of these failures? They stem from unsafety.
Here are just a few real-world examples of cryptographic disasters caused by unsafe programming, undefined behavior, or lack of control:
Heartbleed (2014)
- Cause: Buffer over-read in OpenSSL (written in C)
- Impact: Leaked private keys, passwords, and session data from millions of servers
- Lesson: Unsafe memory access can silently expose secrets
Debian RNG Bug (2006–2008)
- Cause: A developer commented out entropy-gathering code in OpenSSL
- Impact: Generated only 32,768 possible SSH keys across all Debian systems
- Lesson: Cryptographic quality often hinges on deterministic, auditable behavior
Lucky13 Attack (2013)
- Cause: Tiny timing differences in CBC mode padding checks (TLS)
- Impact: Allowed attackers to decrypt data by measuring how long responses took
- Lesson: Timing leaks can invalidate encryption, even with perfect math
JavaScript Crypto Fails
- Cause: Misuse of
Math.random()
or insecure key handling in frontend apps - Impact: Predictable keys, insecure password storage, and non-constant-time comparisons
- Lesson: Languages with hidden optimizations make constant-time logic fragile
Why Rust Helps
Rust’s safety model eliminates whole classes of vulnerabilities:
- No null/dangling pointers
- No uninitialized memory
- Memory-safe concurrency
- Deterministic behavior at runtime (no GC pauses, no JIT surprise)
You still have to design crypto carefully, but with Rust, you’re not building it on quicksand.
Writing secure cryptography in unsafe languages is like writing legal contracts with disappearing ink.
First Code: A Naive XOR Encryptor
Let’s write our first cryptographic algorithm — or at least something that looks like one.
We’ll implement a simple XOR cipher. This method is insecure and should never be used in real applications — but it’s the perfect teaching tool.
What’s a Cipher?
A cipher is just a method to transform readable data (plaintext) into unreadable data (ciphertext) using a key — and vice versa.
🧭 Word Origin — “Cipher” The word comes from the Arabic “ṣifr” (صفر), meaning “zero” or “empty”. It passed through Latin (cifra), then into French and English as cipher.
What started as a symbol for “nothing” evolved into a word for secret writing — and eventually, encryption algorithms.
What is XOR?
XOR stands for “exclusive or”, a bitwise operation:
A | B | A XOR B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
In short: XOR returns 1 if the bits differ, 0 if they’re the same.
The XOR operation flips bits when they differ:
1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
When used for encryption:
cipher = plaintext ^ key
plaintext = cipher ^ key
That’s why XOR can be used to encrypt and decrypt data — if you XOR something twice with the same key, you get the original back.
✅ Simple, reversible, fast — but also dangerously weak when misused.
XOR, Bit by Bit
To truly understand XOR in cryptography, it helps to look at bit-level behavior.
Let’s say you compute:
100 ^ 1
This doesn’t mean 100 to the power of 1. In Rust, ^ is the bitwise XOR operator.
Step-by-step:
100 = 0110 0100
1 = 0000 0001
---------------
XOR = 0110 0101 = 101
✅ Each bit is compared: If they’re different → 1 If they’re the same → 0
100 ^ 1 = 101
This is what makes XOR useful: you can toggle bits with a key, and reverse it by applying the same key again.
Why This?
This example teaches you:
- The reversible nature of XOR (
a ^ b ^ b == a
) - Handling bytes and slices in Rust
- Thinking about encryption as a transformation
- Why key reuse and simplicity are dangerous
Naive XOR in Rust
Here’s how to implement a basic XOR encryptor in Rust:
Filename: src/main.rs
fn main() { let message = b"hello world"; let key = b"key"; let encrypted = xor_encrypt(message, key); let decrypted = xor_encrypt(&encrypted, key); println!("Encrypted: {:x?}", encrypted); println!("Decrypted: {}", String::from_utf8_lossy(&decrypted)); } pub fn xor_encrypt(input: &[u8], key: &[u8]) -> Vec<u8> { input .iter() .enumerate() .map(|(i, &byte)| byte ^ key[i % key.len()]) .collect() }
Output
The output will show the encrypted bytes (in hex) and the original decrypted message.
What’s Wrong With This Cipher?
- Key reuse makes patterns obvious
- No randomness or initialization vector (IV)
- Susceptible to frequency analysis attacks
This cipher is insecure — but it demonstrates important cryptographic concepts:
- Reversibility
- Byte-wise transformations
- Why randomness and key handling matter
You’ll build on this when implementing real-world ciphers like ChaCha20 or AES.
Tooling Up
Before we dive into cryptographic primitives, here’s a quick look at tools that can support your Rust development journey — especially if you plan to write your own crypto libraries.
None of these tools are required to read or complete the following chapters.
If you already havecargo
installed, you’re good to go!
That said, for readers who want to build clean, secure, and testable codebases, these tools are worth bookmarking:
Code Quality
- rustfmt — auto-formats code to keep it idiomatic
- clippy — catches common pitfalls and non-idiomatic patterns
Testing & Fuzzing
- proptest — property-based testing for edge case discovery
- cargo-fuzz — fuzz testing to uncover panics and vulnerabilities
Security & Auditing
- cargo-audit — alerts you to vulnerable crates
- cargo-geiger — scans for
unsafe
code
Benchmarking & Debugging
- Criterion.rs — precise performance benchmarks
- cargo-expand — view macro-expanded code (useful when using
#[derive(...)]
)
As you gain experience, integrating these tools will help ensure your cryptographic code is not only correct — but robust, maintainable, and audit-friendly.
Try It Yourself
Want to skip the setup and jump right into coding?
👉 Use the Sealed in Rust Starter Template — a minimal Rust project preconfigured with the tools mentioned above.
git clone https://github.com/vinecksie/sealed-starter.git
cd sealed-starter
cargo test
Symmetric Ciphers: XOR, AES, ChaCha20 & Beyond
🔐 Used in: VPNs, TLS (post-handshake), disk encryption, messaging apps
✅ Still foundational in modern cryptography.
What Are Symmetric Ciphers?
Symmetric ciphers use the same key for both encryption and decryption. Unlike public-key cryptography, they don’t offer key exchange—but they are much faster, making them ideal for bulk data encryption.
They are used everywhere: encrypted file systems, secure communications, and even inside protocols like TLS (after the handshake).
XOR Cipher — Simplicity That Teaches
⚠️ Insecure. Demonstration-only (used in educational demos, malware obfuscation )
Watch it on my Fearless in Rust channel: XOR Cipher in Rust - Step by Step
We first explored XOR encryption in Section 1.4: First Code — A Naive XOR Encryptor, where we built a full working example from scratch.
XOR is the simplest symmetric cipher: each byte of the message is XORed with a repeating key. Reversibility is built-in — XORing twice with the same key restores the original.
fn main() { let message = b"Hi, Rust!"; let key = b"key"; let encrypted = xor_encrypt(message, key); let decrypted = xor_encrypt(&encrypted, key); println!("Encrypted: {:x?}", encrypted); println!("Decrypted: {}", String::from_utf8_lossy(&decrypted)); } pub fn xor_encrypt(input: &[u8], key: &[u8]) -> Vec<u8> { input .iter() .enumerate() .map(|(i, &byte)| byte ^ key[i % key.len()]) .collect() }
🟢 Conclusion XOR encryption is reversible and stateless, which makes it simple and fast. But it lacks confusion and diffusion, so patterns in the input remain visible — offering no real resistance to cryptanalysis.
Feistel Networks — Foundation of Classic Block Ciphers
⚠️ Cryptographically obsolete, but conceptually important (used in DES, 3DES)
Feistel networks are a clever way to build reversible encryption using any basic function—even if that function itself can’t be reversed. That’s the key idea.
Each round applies a transformation to the data. Multiple rounds are chained to strengthen security.
Each round does the following:
- Takes two halves: Left (L) and Right (R)
- Computes a function f(R, key)
- Updates the pair as:
L₂ = R₁
R₂ = L₁ ⊕ f(R₁, key)
To encrypt, let’s see it in Rust:
fn feistel_round(l: u8, r: u8, k: u8) -> (u8, u8) { let f = r ^ k; (r, l ^ f) } fn main() { let left1: u8 = 0b1010_1010; // 170 let right1: u8 = 0b0101_0101; // 85 let key: u8 = 0b1111_0000; // 240 let (left2, right2) = feistel_round(left1, right1, key); println!("Encrypted: ({}, {})", left2, right2); }
Decryption reuses the same function f, simply reversing the round transformation:
fn feistel_round(l1: u8, r1: u8, k: u8) -> (u8, u8) { let f = r1 ^ k; (r1, l1 ^ f) } fn feistel_decrypt(l2: u8, r2: u8, k: u8) -> (u8, u8) { let f = l2 ^ k; let l1 = r2 ^ f; (l1, l2) } fn main() { let left1: u8 = 0b1010_1010; // 170 let right1: u8 = 0b0101_0101; // 85 let key: u8 = 0b1111_0000; // 240 let (left2, right2) = feistel_round(left1, right1, key); println!("Encrypted: ({}, {})", left2, right2); let (left_orig, right_orig) = feistel_decrypt(left2, right2, key); println!("Decrypted: ({}, {})", left_orig, right_orig); }
Because encryption produces :
Encrypted → (R, L ⊕ f(R, k))
Let’s define:
- L₁ and R₁ = original input
- L₂ = R₁ and R₂ = L₁ ⊕ f(R₁, k)
We receive (L₂, R₂) and want to recover (L₁, R₁):
-
From encryption, we know L₂ = R₁
- So: R₁ = L₂
-
And: R₂ = L₁ ⊕ f(R₁, k)
- Replace R₁ with L₂
- R₂ = L₁ ⊕ f(L₂, k)
-
Rearranging to get L₁:
- L₁ = R₂ ⊕ f(L₂, k)
So, decryption is
L₁ = R₂ ⊕ f(L₂, k)
R₁ = L₂
🟢 Conclusion
Reversibility comes from XOR being reversible and swapping the halves. Feistel networks let you build reversible encryption even with non-invertible functions. This idea shaped DES and similar ciphers.Not used today due to known vulnerabilities, but conceptually essential.
Substitution–Permutation Networks (SPN)
⚠️ Used in AES, Camellia, and modern block ciphers. Still dominant in current cipher architectures
Substitution-Permutation Networks (SPNs) are a powerful way to build secure block ciphers by layering simple operations repeated across multiple rounds to build a secure cipher.
Each round does the following:
- Substitution – replace each byte using an S-box (non-linear mapping)
- Permutation – reorder bits or bytes to spread influence
- Key mixing – XOR the block with a round key
Decryption reverses these steps in reverse order.
💡 An S-box (substitution box) is a predefined table that maps each input byte to a new output byte. Its goal is to introduce non-linearity — meaning the output doesn’t follow any simple, predictable rule based on the input.
This non-linear mapping ensures that small changes in the input produce unpredictable changes in the output, making it impossible to reverse or model with linear equations — a key requirement for secure encryption.
Let’s walk through a simple encryption of a 4-byte block.
#![allow(unused)] fn main() { use std::convert::TryInto; // Manually defined "shuffled" S-box (shortened for demo) let s_box: [u8; 16] = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ]; // Step 1: Substitution with S-box // ⚠️ input and output (substituted) must have the same size // Otherwise, map() or indexing will panic at runtime let input: [u8; 4] = [0x00, 0x03, 0x07, 0x0F]; let substituted: [u8; 4] = input.map(|b| s_box[b as usize]); // Step 2: Permutation (custom byte reordering) let permuted: [u8; 4] = [ substituted[2], // byte 2 moves to pos 0 substituted[0], // byte 0 → pos 1 substituted[3], // byte 3 → pos 2 substituted[1], // byte 1 → pos 3 ]; // Step 3: XOR with round key let round_key: [u8; 4] = [0xF0, 0x0F, 0xAA, 0x55]; let encrypted: [u8; 4] = permuted .iter() .zip(round_key.iter()) .map(|(a, b)| a ^ b) .collect::<Vec<u8>>() .try_into() .unwrap(); println!("Step | Byte 0 | Byte 1 | Byte 2 | Byte 3"); println!("------------|--------|--------|--------|--------"); println!("Input | {:02X} | {:02X} | {:02X} | {:02X}", input[0], input[1], input[2], input[3]); println!("Substituted | {:02X} | {:02X} | {:02X} | {:02X}", substituted[0], substituted[1], substituted[2], substituted[3]); println!("Permuted | {:02X} | {:02X} | {:02X} | {:02X}", permuted[0], permuted[1], permuted[2], permuted[3]); println!("Encrypted | {:02X} | {:02X} | {:02X} | {:02X}", encrypted[0], encrypted[1], encrypted[2], encrypted[3]); }
To decrypt, reverse the steps in reverse order:
#![allow(unused)] fn main() { use std::convert::TryInto; // Same S-box used for encryption let s_box: [u8; 16] = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, ]; // Generate inverse S-box let mut inverse_s_box = [0u8; 256]; for (i, &val) in s_box.iter().enumerate() { inverse_s_box[val as usize] = i as u8; } // Encrypted block from the previous encryption output let encrypted: [u8; 4] = [0x35, 0x6C, 0xDC, 0x2E]; let round_key: [u8; 4] = [0xF0, 0x0F, 0xAA, 0x55]; // Step 1: Undo XOR with round key let xor_reversed: [u8; 4] = encrypted .iter() .zip(round_key.iter()) .map(|(a, b)| a ^ b) .collect::<Vec<u8>>() .try_into() .unwrap(); // Step 2: Reverse permutation // Remember: original permutation was [2, 0, 3, 1] // So now we must do: [1, 3, 0, 2] let permuted_reversed: [u8; 4] = [ xor_reversed[1], // was originally at index 0 xor_reversed[3], // was at index 1 xor_reversed[0], // was at index 2 xor_reversed[2], // was at index 3 ]; // Step 3: Inverse substitution using inverse_s_box let decrypted: [u8; 4] = permuted_reversed.map(|b| inverse_s_box[b as usize]); println!("Step | Byte 0 | Byte 1 | Byte 2 | Byte 3"); println!("------------|--------|--------|--------|--------"); println!("Encrypted | {:02X} | {:02X} | {:02X} | {:02X}", encrypted[0], encrypted[1], encrypted[2], encrypted[3]); println!("XOR Rev | {:02X} | {:02X} | {:02X} | {:02X}", xor_reversed[0], xor_reversed[1], xor_reversed[2], xor_reversed[3]); println!("Perm Rev | {:02X} | {:02X} | {:02X} | {:02X}", permuted_reversed[0], permuted_reversed[1], permuted_reversed[2], permuted_reversed[3]); println!("Decrypted | {:02X} | {:02X} | {:02X} | {:02X}", decrypted[0], decrypted[1], decrypted[2], decrypted[3]); }
Why it works
- Substitution = confusion → Hide relationships between plaintext and ciphertext
- Permutation = diffusion → Spread input influence across the block
These are Shannon’s two pillars of secure ciphers.
💡 Claude Shannon, widely considered the father of modern cryptography, introduced the concepts of confusion and diffusion in 1949 as the foundation of secure cipher design.
🟢 Conclusion
Substitution-Permutation Networks provide a simple yet powerful structure for building symmetric ciphers. They deliver the critical properties of confusion and diffusion, as first formalized by Claude Shannon in his foundational work on cryptographic security.