Introduction
Hashlib provides secure hashing algorithms for password storage and data integrity.
Hashing
import hashlib
# Basic hashing
data = "hello world"
h = hashlib.sha256(data.encode())
print(h.hexdigest())
# Multiple algorithms
h_md5 = hashlib.md5(data.encode())
h_sha1 = hashlib.sha1(data.encode())
h_sha512 = hashlib.sha512(data.encode())
Password Hashing
import bcrypt
# Hash password
password = "secure_password_123"
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
# Verify password
bcrypt.checkpw(password.encode(), hashed)
HMAC
import hmac
import hashlib
key = b"secret_key"
message = b"message to authenticate"
sig = hmac.new(key, message, hashlib.sha256)
print(sig.hexdigest())
Practice Problems
- Hash files for integrity checking
- Implement password verification
- Use HMAC for message authentication
- Generate secure random tokens
- Store and verify passwords safely