Skip to content

hmac.new() and hmac.digest() construct and discard an extra hash object on the Python fallback path #162718

Not planned

Description

@limadog9

Bug report

On CPython 3.15 and 3.16, passing a BLAKE2b factory to hmac.new() or hmac.digest() constructs three hash objects for a short key. CPython 3.14 constructs two: one for the inner hash and one for the outer hash.

import hashlib
import hmac
from unittest.mock import Mock

for operation in (hmac.new, hmac.digest):
    factory = Mock(wraps=hashlib.blake2b)
    operation(b"k", b"data", factory)
    print(operation.__name__, factory.call_count)
CPython on Linux hmac.new hmac.digest
3.14.10 2 2
3.15.2 3 3
3.16.0a2 3 3
main at 3b3093726ffd 3 3

The extra call comes from #136802. _is_shake_constructor() calls the factory to inspect the resulting object's .name, then discards that object. Both fallback paths immediately call the factory again to create the inner and outer hashes. The one-byte key in the example rules out the additional hash that HMAC legitimately needs for a long key.

I tested a local change on main that checks .name on the first hash object the fallback already needs. Both counts returned to two. With hashlib.blake2b passed directly, median time for hmac.new(b"k", b"data", hashlib.blake2b) went from 2.43 to 2.19 µs per call. For hmac.digest() it went from 2.90 to 2.66 µs. These were ten alternating runs of 150,000 calls per implementation on the same interpreter, pinned to one CPU.

The existing test_hmac suite passed with three skips. I also checked that both fallback paths still raised ValueError for a factory returning hashlib.shake_128()

CPython versions tested on:

3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    on Nov 27, 2026
  2. picnixz commented on Nov 27, 2026

    @picnixz
    Member

    It is not a concern. The operations are cheap and re the fallbacks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions