Part 6: Number Theory and Cryptography

Part of the Mathematics for Programming 101 Series

The Security Incident That Taught Me Number Theory

I was reviewing a JWT token implementation. The tokens were predictable.

Someone had used:

token_id = int(time.time())  # Timestamp as token ID

I could predict future tokens. Generate a valid token for 10 seconds in the future, use it before it's issued.

The fix required understanding modular arithmetic and prime numbers:

import secrets

# Cryptographically secure random
token_id = secrets.randbelow(2**128)  # 128-bit random number

# Or use prime field arithmetic
p = 2**127 - 1  # Mersenne prime
token_id = secrets.randbelow(p)

That's when I realized: Number theory isn't abstract mathematicsβ€”it's the foundation of security in every system we build.

Modular Arithmetic: Clock Mathematics

The Basics

Modular arithmetic is like a clock: numbers wrap around at a certain value (the modulus).

Real Application: Hash Tables

Hash tables use modular arithmetic to map keys to buckets:

Modular Exponentiation

Computing large powers efficiently (crucial for cryptography):

Prime Numbers: Building Blocks of Cryptography

Testing for Primes

Generating Prime Numbers

Greatest Common Divisor (GCD)

GCD is fundamental to cryptography and number theory.

Modular Multiplicative Inverse

Critical for decryption in RSA:

RSA Encryption (Simplified)

Understanding the math behind RSA:

Hashing and Checksums

Using modular arithmetic for data integrity:

Chinese Remainder Theorem

Solving systems of modular equations:

Real-World Application: Password Storage

Key Takeaways

  • Modular arithmetic powers hash tables, cryptography, and cyclic operations

  • Prime numbers are the foundation of modern encryption (RSA, Diffie-Hellman)

  • GCD and modular inverses enable cryptographic operations

  • Number theory isn't abstractβ€”it secures every HTTPS connection

  • Efficient algorithms (modular exponentiation, Miller-Rabin) make cryptography practical

  • Understanding the math helps you use crypto libraries correctly and securely

What's Next

In the final article, we'll explore graph theory and algorithmsβ€”the mathematics behind networks, routing, dependencies, and social systems.

You'll learn:

  • Graph representations and traversals

  • Shortest path algorithms

  • Network flow and optimization

  • Real-world graph applications

Continue to Part 7: Graph Theory and Algorithms β†’


Last updated