Skip to content

Instantly share code, notes, and snippets.

@KenjiOhtsuka
Created December 2, 2023 02:56
Show Gist options
  • Save KenjiOhtsuka/fb2dccee29847b4783d1824012867844 to your computer and use it in GitHub Desktop.
Save KenjiOhtsuka/fb2dccee29847b4783d1824012867844 to your computer and use it in GitHub Desktop.
HMAC (SHA-256) implementation
# HMAC with SHA-256
def sha256(message):
# SHA-256 implementation
import hashlib
return hashlib.sha256(message).digest()
def xor(a, b):
# XOR two byte strings
return bytes([x ^ y for x, y in zip(a, b)])
def hmac_sha256(key, message):
"""
HMAC-SHA256 implementation
>>> text = b"Hi There"
>>> key = b'\x0b' * 20
>>> a = hmac_sha256(key, text).hex()
>>> import hmac
>>> b = hmac.new(key, text.encode('ascii'), hashlib.sha256).digest().hex()
>>> a == b
True
>>> text = b"Hello" * 100
>>> key = b'1234567890' * 100
>>> a = hmac_sha256(key, text).hex()
>>> import hmac
>>> b = hmac.new(key, text.encode('ascii'), hashlib.sha256).digest().hex()
>>> a == b
True
:param key:
:param message:
:return:
"""
if len(key) > 64:
key = sha256(key)
if len(key) < 64:
key = key + b'\x00' * (64 - len(key))
o_key_pad = xor(b'\x5c' * 64, key)
i_key_pad = xor(b'\x36' * 64, key)
return sha256(o_key_pad + sha256(i_key_pad + message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment