Skip to content

Commit 69d3f50

Browse files
stratosphersipa
andcommitted
[test/crypto] Add HMAC-based Key Derivation Function (HKDF)
Co-authored-by: Pieter Wuille <[email protected]>
1 parent 08a4a56 commit 69d3f50

File tree

1 file changed

+33
-0
lines changed
  • test/functional/test_framework/crypto

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2023 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
6+
"""Test-only HKDF-SHA256 implementation
7+
8+
It is designed for ease of understanding, not performance.
9+
10+
WARNING: This code is slow and trivially vulnerable to side channel attacks. Do not use for
11+
anything but tests.
12+
"""
13+
14+
import hashlib
15+
import hmac
16+
17+
18+
def hmac_sha256(key, data):
19+
"""Compute HMAC-SHA256 from specified byte arrays key and data."""
20+
return hmac.new(key, data, hashlib.sha256).digest()
21+
22+
23+
def hkdf_sha256(length, ikm, salt, info):
24+
"""Derive a key using HKDF-SHA256."""
25+
if len(salt) == 0:
26+
salt = bytes([0] * 32)
27+
prk = hmac_sha256(salt, ikm)
28+
t = b""
29+
okm = b""
30+
for i in range((length + 32 - 1) // 32):
31+
t = hmac_sha256(prk, t + info + bytes([i + 1]))
32+
okm += t
33+
return okm[:length]

0 commit comments

Comments
 (0)