Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 23 additions & 16 deletions Lib/hmac.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,27 @@ def digest_wrapper(d=b''):
return digest_wrapper


def _select_blocksize(obj, default, stacklevel=3):
if hasattr(obj, 'block_size'):
blocksize = obj.block_size
if blocksize < 16:
import warnings

warnings.warn(f"block_size of {blocksize} seems too small; "
f"using our default of {default}.",
RuntimeWarning, stacklevel=stacklevel)
blocksize = default
else:
import warnings

warnings.warn("No block_size attribute on given digest object; "
f"Assuming {default}.",
RuntimeWarning, stacklevel=stacklevel)
blocksize = default
return blocksize



class HMAC:
"""RFC 2104 HMAC class. Also complies with RFC 4231.

Expand Down Expand Up @@ -116,8 +137,6 @@ def _init_builtin_hmac(self, key, msg, digestmod):
self.block_size = self._hmac.block_size

def _init_old(self, key, msg, digestmod):
import warnings

digest_cons = _get_digest_constructor(digestmod)
if _is_shake_constructor(digest_cons):
raise ValueError(f"unsupported hash algorithm {digestmod}")
Expand All @@ -127,19 +146,7 @@ def _init_old(self, key, msg, digestmod):
self._inner = digest_cons()
self.digest_size = self._inner.digest_size

if hasattr(self._inner, 'block_size'):
blocksize = self._inner.block_size
if blocksize < 16:
warnings.warn(f"block_size of {blocksize} seems too small; "
f"using our default of {self.blocksize}.",
RuntimeWarning, 2)
blocksize = self.blocksize # pragma: no cover
else:
warnings.warn("No block_size attribute on given digest object; "
f"Assuming {self.blocksize}.",
RuntimeWarning, 2)
blocksize = self.blocksize # pragma: no cover

blocksize = _select_blocksize(self._inner, self.blocksize)
if len(key) > blocksize:
key = digest_cons(key).digest()

Expand Down Expand Up @@ -272,7 +279,7 @@ def _compute_digest_fallback(key, msg, digest):
raise ValueError(f"unsupported hash algorithm {digest}")
inner = digest_cons()
outer = digest_cons()
blocksize = getattr(inner, 'block_size', 64)
blocksize = _select_blocksize(inner, HMAC.blocksize)
if len(key) > blocksize:
key = digest_cons(key).digest()
key = key.ljust(blocksize, b'\0')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Ensure that :func:`hmac.digest` and :meth:`hmac.HMAC.digest` output
identical values when using a digest's block size smaller than 16. Patch by
Bénédikt Tran.
Loading