Hashing and secrets in Python
Digests for integrity, hmac for authenticity, secrets for tokens.
import hashlib
import hmac
import secrets
payload = b"lang=python&tpm=104"
print(hashlib.sha256(payload).hexdigest()[:16])
print(hashlib.blake2b(payload, digest_size=8).hexdigest())
key = b"shared-secret"
signature = hmac.new(key, payload, hashlib.sha256).hexdigest()
print(hmac.compare_digest(signature, signature))
print(len(secrets.token_urlsafe(32)), secrets.randbelow(10))
How it works
hashlibdigests bytes, not text — encode first.hmac.compare_digestavoids a timing leak.secretsis the right source for anything security-facing.
Keywords and builtins used here
lenprint
The run, in numbers
- Lines
- 13
- Characters to type
- 380
- Tokens
- 100
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 55 seconds.
Step 1 of 2 in Bytes & secrets, step 30 of 41 in Domain tools.