hkdf.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2023-present 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]
  34