Skip to content

Cryptography Basics: Hashing and Secure Randomness

Beginning of the lesson

Cryptography Basics: Hashing and Secure Randomness

Use Python's standard-library crypto primitives correctly — and know their limits

Big Idea: Real applications constantly need to verify integrity, authenticate messages, generate unguessable tokens, and store passwords safely. Python ships correct, battle-tested tools for all of these: hashlib, hmac and secrets. The skill is not writing crypto — it is choosing the right primitive and using it without the classic footguns (using random for security, storing raw hashes as passwords, or comparing secrets with ==).
By the end you will be able to:
  • distinguish hashing, encryption and encoding and pick the right one,
  • compute content hashes with hashlib, including large files streamed in chunks,
  • authenticate messages with hmac and compare secrets in constant time,
  • generate secure tokens and random values with secrets instead of random,
  • store passwords with a salted, slow key-derivation function (scrypt / PBKDF2),
  • explain why you must never invent your own cryptography.

1. Three things people confuse: hashing vs encryption vs encoding

Before touching a single API, fix the mental model. These three operations look similar (bytes in, bytes out) but solve completely different problems.

OperationReversible?Needs a key?Purpose
Encoding (base64, hex, UTF-8)Yes, triviallyNoRepresent bytes in another alphabet. Not security.
Hashing (SHA-256)No (one-way)NoFixed-size fingerprint of data; integrity, deduplication, lookup.
Encryption (AES)Yes, with the keyYesKeep data confidential so only key holders can read it.

The single most common beginner error is treating encoding as security. Base64 is not encryption — anyone can decode it in one line. And a hash is not encryption either: there is no key and no way to get the original back. A hash answers "are these two things identical?" and "has this data been tampered with?", never "hide this so I can read it later".

Rule of thumb: need it back later → encryption. Only need to check it matches → hashing. Just changing alphabets → encoding. This course covers hashing and secure randomness; encryption (the cryptography package's AES-GCM / Fernet) is a separate, key-management-heavy topic.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers