Skip to content

Commit 56005fb

Browse files
authored
speed up HKDF on longer expands by copying the context (#12994)
1 parent a94ec9d commit 56005fb

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/cryptography/hazmat/primitives/kdf/hkdf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,9 @@ def _expand(self, key_material: utils.Buffer) -> bytes:
7878
output = [b""]
7979
counter = 1
8080

81+
h_prime = hmac.HMAC(key_material, self._algorithm)
8182
while self._algorithm.digest_size * (len(output) - 1) < self._length:
82-
h = hmac.HMAC(key_material, self._algorithm)
83+
h = h_prime.copy()
8384
h.update(output[-1])
8485
h.update(self._info)
8586
h.update(bytes([counter]))

tests/bench/test_hkdf.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# This file is dual licensed under the terms of the Apache License, Version
2+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3+
# for complete details.
4+
5+
from cryptography.hazmat.primitives import hashes
6+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
7+
8+
9+
def test_hkdf(benchmark):
10+
def bench():
11+
hkdf = HKDF(
12+
hashes.SHA512(),
13+
16000,
14+
salt=b"salt",
15+
info=b"info",
16+
)
17+
hkdf.derive(b"0" * 64)
18+
19+
benchmark(bench)

0 commit comments

Comments
 (0)