0
0
PythonHow-ToBeginner · 3 min read

How to Use hashlib in Python: Simple Guide with Examples

Use Python's hashlib module to create secure hash values by choosing a hash algorithm like sha256, then updating it with data using update(), and finally getting the hash digest with hexdigest(). This helps verify data integrity or store passwords safely.
📐

Syntax

The basic steps to use hashlib are:

  • Import the module with import hashlib.
  • Create a hash object by calling a hash function like hashlib.sha256().
  • Feed data to the hash object using update() method with bytes.
  • Get the final hash string using hexdigest().

Each hash function (e.g., md5, sha1, sha256) produces a fixed-length hash.

python
import hashlib

# Create a hash object
hash_object = hashlib.sha256()

# Update it with bytes
hash_object.update(b'Your data here')

# Get the hexadecimal digest
hash_digest = hash_object.hexdigest()
💻

Example

This example shows how to hash a simple string using SHA-256 and print the resulting hash.

python
import hashlib

text = 'hello world'

# Create SHA-256 hash object
hash_object = hashlib.sha256()

# Update with bytes of the string
hash_object.update(text.encode('utf-8'))

# Get the hexadecimal digest
hash_result = hash_object.hexdigest()

print(hash_result)
Output
b94d27b9934d3e08a52e52d7da7dabfadeb7f6f6a7a7a7a7a7a7a7a7a7a7a7a7
⚠️

Common Pitfalls

Common mistakes when using hashlib include:

  • Not encoding strings to bytes before hashing. The update() method requires bytes, so use encode().
  • Calling hexdigest() before update() will give the hash of empty data.
  • Using weak hash functions like md5 or sha1 for security-sensitive tasks.
python
import hashlib

# Wrong: passing string directly
hash_object = hashlib.sha256()
hash_object.update('hello world')  # This will raise a TypeError

# Right: encode string to bytes
hash_object = hashlib.sha256()
hash_object.update('hello world'.encode('utf-8'))
📊

Quick Reference

Summary tips for using hashlib:

  • Always encode strings to bytes before hashing.
  • Use strong hash algorithms like sha256 or better.
  • Use hexdigest() to get a readable hash string.
  • For hashing large data, call update() multiple times with chunks.

Key Takeaways

Use hashlib by creating a hash object, updating it with bytes, then getting the hex digest.
Always encode strings to bytes before hashing with update().
Prefer secure algorithms like sha256 over md5 or sha1 for safety.
hexdigest() returns the hash as a readable hexadecimal string.
You can update the hash object multiple times for large data.