typestar

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

  1. hashlib digests bytes, not text — encode first.
  2. hmac.compare_digest avoids a timing leak.
  3. secrets is the right source for anything security-facing.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Bytes & secrets, step 30 of 41 in Domain tools.

← Previous Next →