Some text some message..
Back 🌟 Python hashlib Library Cheat Sheet 20 Aug, 2025

1️⃣ What is hashlib?

hashlib is a built-in Python module for secure hashing algorithms.
It helps you convert data (like strings, files) into fixed-size, unique hash values.

✅ Common uses:

  • Password storage

  • File integrity checks

  • Digital signatures


2️⃣ How Hashing Works

Hashing takes any input → outputs a fixed-length string (digest).

Input → Hash Function → Hash (Digest)

Example:

import hashlib

text = "Abhishek"
hash_object = hashlib.sha256(text.encode())
print(hash_object.hexdigest())

Output:

6f7c3a... (fixed-length string)

3️⃣ Popular Hash Algorithms

Algorithm Digest Size Notes
md5 128-bit Fast but not secure (use for checksums)
sha1 160-bit Slightly better but vulnerable
sha224 224-bit Stronger than sha1
sha256 256-bit Very common & secure
sha384 384-bit More secure
sha512 512-bit Very secure, slower

💡 Tip: For passwords or sensitive info → Use sha256 or higher.


4️⃣ Basic Usage

import hashlib

# 1. Encode your text
text = "Hello World"
encoded_text = text.encode()

# 2. Create a hash object
hash_obj = hashlib.sha256(encoded_text)

# 3. Get the hexadecimal digest
hex_digest = hash_obj.hexdigest()

print(hex_digest)

5️⃣ Hashing Large Data (Files)

import hashlib

def hash_file(filename):
    hasher = hashlib.sha256()
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

print(hash_file("example.pdf"))
  • Reads file in chunks → saves memory

  • Good for big files


6️⃣ Why hashlib is Awesome

  • 🔒 Secure hashing (SHA family)

  • ⚡ Fast for strings and files

  • 📏 Fixed output length → easy comparison

  • ✅ Built-in, no extra installation


7️⃣ Fun Visual Idea

Text / File → [hashlib] → Hash (Unique Fingerprint)
          🖊️ SHA256, MD5, SHA1 ...