Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active November 22, 2021 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/c13a7ceab292e44b350cf58633f22b1b to your computer and use it in GitHub Desktop.
Save nakagami/c13a7ceab292e44b350cf58633f22b1b to your computer and use it in GitHub Desktop.
import hashlib
import binascii
def hmac_sha256_digest(key, msg):
pad_key = key + b'\x00' * (64 - (len(key) % 64))
ik = bytes([0x36 ^ b for b in pad_key])
ok = bytes([0x5c ^ b for b in pad_key])
return hashlib.sha256(ok + hashlib.sha256(ik+msg).digest()).digest()
def pbkdf2_hmac_sha256(password_bytes, salt, iterations):
# hashlib.pbkdf2_hmac('sha256', password_bytes, salt, iterations)
_u1 = hmac_sha256_digest(password_bytes, salt+b'\x00\x00\x00\x01')
_ui = int.from_bytes(_u1, 'big')
for _ in range(iterations - 1):
_u1 = hmac_sha256_digest(password_bytes, _u1)
_ui ^= int.from_bytes(_u1, 'big')
return _ui.to_bytes(32, 'big')
password = b'secret'
salt = b'salt'
n = 1000
assert hashlib.pbkdf2_hmac('sha256', password, salt, n) == pbkdf2_hmac_sha256(password, salt, n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment