Predict the output
What does the last line print?
import hashlib
import hmac
import os
def hash_password(pw: str) -> str:
salt = os.urandom(16)
dk = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1)
return f"scrypt$16384$8$1${salt.hex()}${dk.hex()}"
def check(pw: str, stored: str) -> bool:
_, n, r, p, salt, dk = stored.split("$")
got = hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt),
n=int(n), r=int(r), p=int(p))
return hmac.compare_digest(got.hex(), dk)
h1, h2 = hash_password("hunter2"), hash_password("hunter2")
print(h1 != h2, check("hunter2", h1), check("hunter3", h1))Hint 1 of 1
What does a random salt do to identical passwords?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True True False
Correct. Random salts make the two hashes differ; the right password verifies and a wrong one doesn't.
Each call draws a fresh 16-byte salt, so the same password gives a different stored string. check reads that salt back out of the string, recomputes scrypt and compares, so only the right password matches.
Why not the others?
- B
False True False. Each hash gets its own random salt, so they differ. - C
True True True. A different password gives a different derived key. - D
True False False. check uses the salt stored in the hash.