Safe Password Hashing with PBKDF2 & Salt
Raw SHA-256 is vulnerable to rainbow table attacks. Use `hashlib.pbkdf2_hmac` with a random unique salt and high iteration counts to hash passwords securely 🧂.
import hashlib, secrets
password = b"SuperSecretPassword"
salt = secrets.token_bytes(16)
# 100,000 iterations of HMAC-SHA256:
key = hashlib.pbkdf2_hmac("sha256", password, salt, 100000)
print(f"Derived Key (hex): {key.hex()[:32]}... 🛡️")
# 114. Safe Password Hashing with PBKDF2 & Salt Raw SHA-256 is vulnerable to rainbow table attacks. Use `hashlib.pbkdf2_hmac` with a random unique salt and high iteration counts to hash passwords securely 🧂. ```python import hashlib, secrets password = b"SuperSecretPassword" salt = secrets.token_bytes(16) # 100,000 iterations of HMAC-SHA256: key = hashlib.pbkdf2_hmac("sha256", password, salt, 100000) print(f"Derived Key (hex): {key.hex()[:32]}... 🛡️") ``` A random cryptographic salt prevents identical passwords from having identical hashes, rendering precomputed rainbow tables useless! 🧂 --- ### Question What security vulnerability does adding a unique random salt to password hashing eliminate? 🧠 - [ ] a. Rainbow table attacks (precomputed hash lookups) 🧂 - [ ] b. SQL injection attacks - [ ] c. Buffer overflow vulnerabilities - [ ] d. Cross-site scripting (XSS) --- ### Challenge Import `hashlib`. Hash `b'pass123'` using `hashlib.pbkdf2_hmac('sha256', b'pass123', b'fixed_salt', 1000)`. Print `len(key)` in bytes. 🎯 <details> <summary>Solution</summary> ```python import hashlib key = hashlib.pbkdf2_hmac("sha256", b"pass123", b"fixed_salt", 1000) print(len(key)) ``` </details>