Created
December 2, 2023 02:56
-
-
Save KenjiOhtsuka/fb2dccee29847b4783d1824012867844 to your computer and use it in GitHub Desktop.
HMAC (SHA-256) implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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