Python HMAC Code Example (Online Runner)
Python HMAC examples with selectable hash algorithms, input encodings, and hex/Base64 output to match the online tool.
Online calculator: use the site HMAC tool.
Calculation method
The online tool lets you choose the hash algorithm, message encoding, key encoding, and output encoding. The helper below
mirrors those options using Python’s hmac and hashlib modules.
Note: RIPEMD-160 depends on your OpenSSL build; if it is missing, install pycryptodome and use Crypto.Hash.RIPEMD160.
Implementation notes
- Package: built-in
hmacandhashlib(plus optionalpycryptodomefor RIPEMD-160). - Implementation: the helper normalizes message/key encodings and supports hex/base64 output to match the UI.
- Notes: HMAC is a keyed MAC, not a hash; always keep the key secret. Use
hmac.compare_digestfor timing-safe comparisons when verifying tags.
python
import base64
import hashlib
import hmac
from typing import Literal
Algorithm = Literal[
"sha1",
"sha224",
"sha256",
"sha384",
"sha512",
"sha3-256",
"sha3-512",
"ripemd160",
"md5",
]
Encoding = Literal["utf8", "hex", "base64"]
OutputEncoding = Literal["hex", "base64"]
def _decode(value: str, encoding: Encoding) -> bytes:
if encoding == "hex":
return bytes.fromhex(value)
if encoding == "base64":
return base64.b64decode(value)
return value.encode("utf-8")
def _encode(value: bytes, encoding: OutputEncoding) -> str:
return base64.b64encode(value).decode("ascii") if encoding == "base64" else value.hex()
def _digestmod(algorithm: Algorithm):
if algorithm == "sha3-256":
return hashlib.sha3_256
if algorithm == "sha3-512":
return hashlib.sha3_512
if algorithm == "ripemd160":
return lambda data=b"": hashlib.new("ripemd160", data)
return getattr(hashlib, algorithm)
def hmac_digest(
message: str,
key: str,
algorithm: Algorithm = "sha256",
message_encoding: Encoding = "utf8",
key_encoding: Encoding = "utf8",
output_encoding: OutputEncoding = "hex",
) -> str:
msg_bytes = _decode(message, message_encoding)
key_bytes = _decode(key, key_encoding)
mac = hmac.new(key_bytes, msg_bytes, _digestmod(algorithm))
return _encode(mac.digest(), output_encoding)
# Example usage
message = "hello"
key = "secret"
print(hmac_digest(message, key, algorithm="sha256"))
print(hmac_digest("68656c6c6f", key, algorithm="sha256", message_encoding="hex"))
print(hmac_digest(message, "c2VjcmV0", algorithm="sha256", key_encoding="base64", output_encoding="base64"))
File HMAC example
python
from pathlib import Path
from typing import Literal
import hashlib
import hmac
import tempfile
Algorithm = Literal[
"sha1",
"sha224",
"sha256",
"sha384",
"sha512",
"sha3-256",
"sha3-512",
"ripemd160",
"md5",
]
def _digestmod(algorithm: Algorithm):
if algorithm == "sha3-256":
return hashlib.sha3_256
if algorithm == "sha3-512":
return hashlib.sha3_512
if algorithm == "ripemd160":
return lambda data=b"": hashlib.new("ripemd160", data)
return getattr(hashlib, algorithm)
def hmac_file(path: Path, key: str, algorithm: Algorithm = "sha256") -> str:
hasher = hmac.new(key.encode("utf-8"), digestmod=_digestmod(algorithm))
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest()
with tempfile.TemporaryDirectory() as temp_dir:
sample_path = Path(temp_dir) / "sample.bin"
sample_path.write_bytes(b"hello")
print(hmac_file(sample_path, key="secret", algorithm="sha256"))Complete script (implementation + tests)
python
import hashlib
import hmac
def run_tests() -> None:
expected = "88aab3ede8d3adf94d26ab90d3bafd4a2083070c3bcce9c014ee04a443847c0b"
actual = hmac.new(b"secret", b"hello", hashlib.sha256).hexdigest()
assert actual == expected, "HMAC-SHA256 mismatch"
print("All HMAC tests passed.")
if __name__ == "__main__":
run_tests()