/ RNS / Cryptography / HKDF.py
HKDF.py
 1  # Reticulum License
 2  #
 3  # Copyright (c) 2016-2025 Mark Qvist
 4  #
 5  # Permission is hereby granted, free of charge, to any person obtaining a copy
 6  # of this software and associated documentation files (the "Software"), to deal
 7  # in the Software without restriction, including without limitation the rights
 8  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 9  # copies of the Software, and to permit persons to whom the Software is
10  # furnished to do so, subject to the following conditions:
11  #
12  # - The Software shall not be used in any kind of system which includes amongst
13  #   its functions the ability to purposefully do harm to human beings.
14  #
15  # - The Software shall not be used, directly or indirectly, in the creation of
16  #   an artificial intelligence, machine learning or language model training
17  #   dataset, including but not limited to any use that contributes to the
18  #   training or development of such a model or algorithm.
19  #
20  # - The above copyright notice and this permission notice shall be included in
21  #   all copies or substantial portions of the Software.
22  #
23  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29  # SOFTWARE.
30  
31  import hashlib
32  from math import ceil
33  from RNS.Cryptography import HMAC
34  
35  def hkdf(length=None, derive_from=None, salt=None, context=None):
36      hash_len = 32
37  
38      def hmac_sha256(key, data):
39          return HMAC.new(key, data).digest()
40  
41      if length == None or length < 1:
42          raise ValueError("Invalid output key length")
43  
44      if derive_from == None or derive_from == "":
45          raise ValueError("Cannot derive key from empty input material")
46  
47      if salt == None or len(salt) == 0:
48          salt = bytes([0] * hash_len)
49  
50      if context == None:
51          context = b""
52  
53      pseudorandom_key = hmac_sha256(salt, derive_from)
54  
55      block = b""
56      derived = b""
57  
58      for i in range(ceil(length / hash_len)):
59          block = hmac_sha256(pseudorandom_key, block + context + bytes([(i + 1)%(0xFF+1)]))
60          derived += block
61  
62      return derived[:length]