KDF.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. # coding=utf-8
  2. #
  3. # KDF.py : a collection of Key Derivation Functions
  4. #
  5. # Part of the Python Cryptography Toolkit
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. import re
  25. import struct
  26. from functools import reduce
  27. from Crypto.Util.py3compat import (tobytes, bord, _copy_bytes, iter_range,
  28. tostr, bchr, bstr)
  29. from Crypto.Hash import SHA1, SHA256, HMAC, CMAC, BLAKE2s
  30. from Crypto.Util.strxor import strxor
  31. from Crypto.Random import get_random_bytes
  32. from Crypto.Util.number import size as bit_size, long_to_bytes, bytes_to_long
  33. from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  34. create_string_buffer,
  35. get_raw_buffer, c_size_t)
  36. _raw_salsa20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._Salsa20",
  37. """
  38. int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
  39. uint8_t *out);
  40. """)
  41. _raw_scrypt_lib = load_pycryptodome_raw_lib("Crypto.Protocol._scrypt",
  42. """
  43. typedef int (core_t)(const uint8_t [64], const uint8_t [64], uint8_t [64]);
  44. int scryptROMix(const uint8_t *data_in, uint8_t *data_out,
  45. size_t data_len, unsigned N, core_t *core);
  46. """)
  47. def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
  48. """Derive one key from a password (or passphrase).
  49. This function performs key derivation according to an old version of
  50. the PKCS#5 standard (v1.5) or `RFC2898
  51. <https://www.ietf.org/rfc/rfc2898.txt>`_.
  52. Args:
  53. password (string):
  54. The secret password to generate the key from.
  55. salt (byte string):
  56. An 8 byte string to use for better protection from dictionary attacks.
  57. This value does not need to be kept secret, but it should be randomly
  58. chosen for each derivation.
  59. dkLen (integer):
  60. The length of the desired key. The default is 16 bytes, suitable for
  61. instance for :mod:`Crypto.Cipher.AES`.
  62. count (integer):
  63. The number of iterations to carry out. The recommendation is 1000 or
  64. more.
  65. hashAlgo (module):
  66. The hash algorithm to use, as a module or an object from the :mod:`Crypto.Hash` package.
  67. The digest length must be no shorter than ``dkLen``.
  68. The default algorithm is :mod:`Crypto.Hash.SHA1`.
  69. Return:
  70. A byte string of length ``dkLen`` that can be used as key.
  71. """
  72. if not hashAlgo:
  73. hashAlgo = SHA1
  74. password = tobytes(password)
  75. pHash = hashAlgo.new(password+salt)
  76. digest = pHash.digest_size
  77. if dkLen > digest:
  78. raise TypeError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
  79. if len(salt) != 8:
  80. raise ValueError("Salt is not 8 bytes long (%d bytes instead)." % len(salt))
  81. for i in iter_range(count-1):
  82. pHash = pHash.new(pHash.digest())
  83. return pHash.digest()[:dkLen]
  84. def PBKDF2(password, salt, dkLen=16, count=1000, prf=None, hmac_hash_module=None):
  85. """Derive one or more keys from a password (or passphrase).
  86. This function performs key derivation according to the PKCS#5 standard (v2.0).
  87. Args:
  88. password (string or byte string):
  89. The secret password to generate the key from.
  90. Strings will be encoded as ISO 8859-1 (also known as Latin-1),
  91. which does not allow any characters with codepoints > 255.
  92. salt (string or byte string):
  93. A (byte) string to use for better protection from dictionary attacks.
  94. This value does not need to be kept secret, but it should be randomly
  95. chosen for each derivation. It is recommended to use at least 16 bytes.
  96. Strings will be encoded as ISO 8859-1 (also known as Latin-1),
  97. which does not allow any characters with codepoints > 255.
  98. dkLen (integer):
  99. The cumulative length of the keys to produce.
  100. Due to a flaw in the PBKDF2 design, you should not request more bytes
  101. than the ``prf`` can output. For instance, ``dkLen`` should not exceed
  102. 20 bytes in combination with ``HMAC-SHA1``.
  103. count (integer):
  104. The number of iterations to carry out. The higher the value, the slower
  105. and the more secure the function becomes.
  106. You should find the maximum number of iterations that keeps the
  107. key derivation still acceptable on the slowest hardware you must support.
  108. Although the default value is 1000, **it is recommended to use at least
  109. 1000000 (1 million) iterations**.
  110. prf (callable):
  111. A pseudorandom function. It must be a function that returns a
  112. pseudorandom byte string from two parameters: a secret and a salt.
  113. The slower the algorithm, the more secure the derivation function.
  114. If not specified, **HMAC-SHA1** is used.
  115. hmac_hash_module (module):
  116. A module from ``Crypto.Hash`` implementing a Merkle-Damgard cryptographic
  117. hash, which PBKDF2 must use in combination with HMAC.
  118. This parameter is mutually exclusive with ``prf``.
  119. Return:
  120. A byte string of length ``dkLen`` that can be used as key material.
  121. If you want multiple keys, just break up this string into segments of the desired length.
  122. """
  123. password = tobytes(password)
  124. salt = tobytes(salt)
  125. if prf and hmac_hash_module:
  126. raise ValueError("'prf' and 'hmac_hash_module' are mutually exlusive")
  127. if prf is None and hmac_hash_module is None:
  128. hmac_hash_module = SHA1
  129. if prf or not hasattr(hmac_hash_module, "_pbkdf2_hmac_assist"):
  130. # Generic (and slow) implementation
  131. if prf is None:
  132. prf = lambda p,s: HMAC.new(p, s, hmac_hash_module).digest()
  133. def link(s):
  134. s[0], s[1] = s[1], prf(password, s[1])
  135. return s[0]
  136. key = b''
  137. i = 1
  138. while len(key) < dkLen:
  139. s = [ prf(password, salt + struct.pack(">I", i)) ] * 2
  140. key += reduce(strxor, (link(s) for j in range(count)) )
  141. i += 1
  142. else:
  143. # Optimized implementation
  144. key = b''
  145. i = 1
  146. while len(key)<dkLen:
  147. base = HMAC.new(password, b"", hmac_hash_module)
  148. first_digest = base.copy().update(salt + struct.pack(">I", i)).digest()
  149. key += base._pbkdf2_hmac_assist(first_digest, count)
  150. i += 1
  151. return key[:dkLen]
  152. class _S2V(object):
  153. """String-to-vector PRF as defined in `RFC5297`_.
  154. This class implements a pseudorandom function family
  155. based on CMAC that takes as input a vector of strings.
  156. .. _RFC5297: http://tools.ietf.org/html/rfc5297
  157. """
  158. def __init__(self, key, ciphermod, cipher_params=None):
  159. """Initialize the S2V PRF.
  160. :Parameters:
  161. key : byte string
  162. A secret that can be used as key for CMACs
  163. based on ciphers from ``ciphermod``.
  164. ciphermod : module
  165. A block cipher module from `Crypto.Cipher`.
  166. cipher_params : dictionary
  167. A set of extra parameters to use to create a cipher instance.
  168. """
  169. self._key = _copy_bytes(None, None, key)
  170. self._ciphermod = ciphermod
  171. self._last_string = self._cache = b'\x00' * ciphermod.block_size
  172. # Max number of update() call we can process
  173. self._n_updates = ciphermod.block_size * 8 - 1
  174. if cipher_params is None:
  175. self._cipher_params = {}
  176. else:
  177. self._cipher_params = dict(cipher_params)
  178. @staticmethod
  179. def new(key, ciphermod):
  180. """Create a new S2V PRF.
  181. :Parameters:
  182. key : byte string
  183. A secret that can be used as key for CMACs
  184. based on ciphers from ``ciphermod``.
  185. ciphermod : module
  186. A block cipher module from `Crypto.Cipher`.
  187. """
  188. return _S2V(key, ciphermod)
  189. def _double(self, bs):
  190. doubled = bytes_to_long(bs)<<1
  191. if bord(bs[0]) & 0x80:
  192. doubled ^= 0x87
  193. return long_to_bytes(doubled, len(bs))[-len(bs):]
  194. def update(self, item):
  195. """Pass the next component of the vector.
  196. The maximum number of components you can pass is equal to the block
  197. length of the cipher (in bits) minus 1.
  198. :Parameters:
  199. item : byte string
  200. The next component of the vector.
  201. :Raise TypeError: when the limit on the number of components has been reached.
  202. """
  203. if self._n_updates == 0:
  204. raise TypeError("Too many components passed to S2V")
  205. self._n_updates -= 1
  206. mac = CMAC.new(self._key,
  207. msg=self._last_string,
  208. ciphermod=self._ciphermod,
  209. cipher_params=self._cipher_params)
  210. self._cache = strxor(self._double(self._cache), mac.digest())
  211. self._last_string = _copy_bytes(None, None, item)
  212. def derive(self):
  213. """"Derive a secret from the vector of components.
  214. :Return: a byte string, as long as the block length of the cipher.
  215. """
  216. if len(self._last_string) >= 16:
  217. # xorend
  218. final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
  219. else:
  220. # zero-pad & xor
  221. padded = (self._last_string + b'\x80' + b'\x00' * 15)[:16]
  222. final = strxor(padded, self._double(self._cache))
  223. mac = CMAC.new(self._key,
  224. msg=final,
  225. ciphermod=self._ciphermod,
  226. cipher_params=self._cipher_params)
  227. return mac.digest()
  228. def HKDF(master, key_len, salt, hashmod, num_keys=1, context=None):
  229. """Derive one or more keys from a master secret using
  230. the HMAC-based KDF defined in RFC5869_.
  231. Args:
  232. master (byte string):
  233. The unguessable value used by the KDF to generate the other keys.
  234. It must be a high-entropy secret, though not necessarily uniform.
  235. It must not be a password.
  236. key_len (integer):
  237. The length in bytes of every derived key.
  238. salt (byte string):
  239. A non-secret, reusable value that strengthens the randomness
  240. extraction step.
  241. Ideally, it is as long as the digest size of the chosen hash.
  242. If empty, a string of zeroes in used.
  243. hashmod (module):
  244. A cryptographic hash algorithm from :mod:`Crypto.Hash`.
  245. :mod:`Crypto.Hash.SHA512` is a good choice.
  246. num_keys (integer):
  247. The number of keys to derive. Every key is :data:`key_len` bytes long.
  248. The maximum cumulative length of all keys is
  249. 255 times the digest size.
  250. context (byte string):
  251. Optional identifier describing what the keys are used for.
  252. Return:
  253. A byte string or a tuple of byte strings.
  254. .. _RFC5869: http://tools.ietf.org/html/rfc5869
  255. """
  256. output_len = key_len * num_keys
  257. if output_len > (255 * hashmod.digest_size):
  258. raise ValueError("Too much secret data to derive")
  259. if not salt:
  260. salt = b'\x00' * hashmod.digest_size
  261. if context is None:
  262. context = b""
  263. # Step 1: extract
  264. hmac = HMAC.new(salt, master, digestmod=hashmod)
  265. prk = hmac.digest()
  266. # Step 2: expand
  267. t = [ b"" ]
  268. n = 1
  269. tlen = 0
  270. while tlen < output_len:
  271. hmac = HMAC.new(prk, t[-1] + context + struct.pack('B', n), digestmod=hashmod)
  272. t.append(hmac.digest())
  273. tlen += hashmod.digest_size
  274. n += 1
  275. derived_output = b"".join(t)
  276. if num_keys == 1:
  277. return derived_output[:key_len]
  278. kol = [derived_output[idx:idx + key_len]
  279. for idx in iter_range(0, output_len, key_len)]
  280. return list(kol[:num_keys])
  281. def scrypt(password, salt, key_len, N, r, p, num_keys=1):
  282. """Derive one or more keys from a passphrase.
  283. Args:
  284. password (string):
  285. The secret pass phrase to generate the keys from.
  286. salt (string):
  287. A string to use for better protection from dictionary attacks.
  288. This value does not need to be kept secret,
  289. but it should be randomly chosen for each derivation.
  290. It is recommended to be at least 16 bytes long.
  291. key_len (integer):
  292. The length in bytes of each derived key.
  293. N (integer):
  294. CPU/Memory cost parameter. It must be a power of 2 and less
  295. than :math:`2^{32}`.
  296. r (integer):
  297. Block size parameter.
  298. p (integer):
  299. Parallelization parameter.
  300. It must be no greater than :math:`(2^{32}-1)/(4r)`.
  301. num_keys (integer):
  302. The number of keys to derive. Every key is :data:`key_len` bytes long.
  303. By default, only 1 key is generated.
  304. The maximum cumulative length of all keys is :math:`(2^{32}-1)*32`
  305. (that is, 128TB).
  306. A good choice of parameters *(N, r , p)* was suggested
  307. by Colin Percival in his `presentation in 2009`__:
  308. - *( 2¹⁴, 8, 1 )* for interactive logins (≤100ms)
  309. - *( 2²⁰, 8, 1 )* for file encryption (≤5s)
  310. Return:
  311. A byte string or a tuple of byte strings.
  312. .. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf
  313. """
  314. if 2 ** (bit_size(N) - 1) != N:
  315. raise ValueError("N must be a power of 2")
  316. if N >= 2 ** 32:
  317. raise ValueError("N is too big")
  318. if p > ((2 ** 32 - 1) * 32) // (128 * r):
  319. raise ValueError("p or r are too big")
  320. prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest()
  321. stage_1 = PBKDF2(password, salt, p * 128 * r, 1, prf=prf_hmac_sha256)
  322. scryptROMix = _raw_scrypt_lib.scryptROMix
  323. core = _raw_salsa20_lib.Salsa20_8_core
  324. # Parallelize into p flows
  325. data_out = []
  326. for flow in iter_range(p):
  327. idx = flow * 128 * r
  328. buffer_out = create_string_buffer(128 * r)
  329. result = scryptROMix(stage_1[idx : idx + 128 * r],
  330. buffer_out,
  331. c_size_t(128 * r),
  332. N,
  333. core)
  334. if result:
  335. raise ValueError("Error %X while running scrypt" % result)
  336. data_out += [ get_raw_buffer(buffer_out) ]
  337. dk = PBKDF2(password,
  338. b"".join(data_out),
  339. key_len * num_keys, 1,
  340. prf=prf_hmac_sha256)
  341. if num_keys == 1:
  342. return dk
  343. kol = [dk[idx:idx + key_len]
  344. for idx in iter_range(0, key_len * num_keys, key_len)]
  345. return kol
  346. def _bcrypt_encode(data):
  347. s = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  348. bits = []
  349. for c in data:
  350. bits_c = bin(bord(c))[2:].zfill(8)
  351. bits.append(bstr(bits_c))
  352. bits = b"".join(bits)
  353. bits6 = [ bits[idx:idx+6] for idx in range(0, len(bits), 6) ]
  354. result = []
  355. for g in bits6[:-1]:
  356. idx = int(g, 2)
  357. result.append(s[idx])
  358. g = bits6[-1]
  359. idx = int(g, 2) << (6 - len(g))
  360. result.append(s[idx])
  361. result = "".join(result)
  362. return tobytes(result)
  363. def _bcrypt_decode(data):
  364. s = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  365. bits = []
  366. for c in tostr(data):
  367. idx = s.find(c)
  368. bits6 = bin(idx)[2:].zfill(6)
  369. bits.append(bits6)
  370. bits = "".join(bits)
  371. modulo4 = len(data) % 4
  372. if modulo4 == 1:
  373. raise ValueError("Incorrect length")
  374. elif modulo4 == 2:
  375. bits = bits[:-4]
  376. elif modulo4 == 3:
  377. bits = bits[:-2]
  378. bits8 = [ bits[idx:idx+8] for idx in range(0, len(bits), 8) ]
  379. result = []
  380. for g in bits8:
  381. result.append(bchr(int(g, 2)))
  382. result = b"".join(result)
  383. return result
  384. def _bcrypt_hash(password, cost, salt, constant, invert):
  385. from Crypto.Cipher import _EKSBlowfish
  386. if len(password) > 72:
  387. raise ValueError("The password is too long. It must be 72 bytes at most.")
  388. if not (4 <= cost <= 31):
  389. raise ValueError("bcrypt cost factor must be in the range 4..31")
  390. cipher = _EKSBlowfish.new(password, _EKSBlowfish.MODE_ECB, salt, cost, invert)
  391. ctext = constant
  392. for _ in range(64):
  393. ctext = cipher.encrypt(ctext)
  394. return ctext
  395. def bcrypt(password, cost, salt=None):
  396. """Hash a password into a key, using the OpenBSD bcrypt protocol.
  397. Args:
  398. password (byte string or string):
  399. The secret password or pass phrase.
  400. It must be at most 72 bytes long.
  401. It must not contain the zero byte.
  402. Unicode strings will be encoded as UTF-8.
  403. cost (integer):
  404. The exponential factor that makes it slower to compute the hash.
  405. It must be in the range 4 to 31.
  406. A value of at least 12 is recommended.
  407. salt (byte string):
  408. Optional. Random byte string to thwarts dictionary and rainbow table
  409. attacks. It must be 16 bytes long.
  410. If not passed, a random value is generated.
  411. Return (byte string):
  412. The bcrypt hash
  413. Raises:
  414. ValueError: if password is longer than 72 bytes or if it contains the zero byte
  415. """
  416. password = tobytes(password, "utf-8")
  417. if password.find(bchr(0)[0]) != -1:
  418. raise ValueError("The password contains the zero byte")
  419. if len(password) < 72:
  420. password += b"\x00"
  421. if salt is None:
  422. salt = get_random_bytes(16)
  423. if len(salt) != 16:
  424. raise ValueError("bcrypt salt must be 16 bytes long")
  425. ctext = _bcrypt_hash(password, cost, salt, b"OrpheanBeholderScryDoubt", True)
  426. cost_enc = b"$" + bstr(str(cost).zfill(2))
  427. salt_enc = b"$" + _bcrypt_encode(salt)
  428. hash_enc = _bcrypt_encode(ctext[:-1]) # only use 23 bytes, not 24
  429. return b"$2a" + cost_enc + salt_enc + hash_enc
  430. def bcrypt_check(password, bcrypt_hash):
  431. """Verify if the provided password matches the given bcrypt hash.
  432. Args:
  433. password (byte string or string):
  434. The secret password or pass phrase to test.
  435. It must be at most 72 bytes long.
  436. It must not contain the zero byte.
  437. Unicode strings will be encoded as UTF-8.
  438. bcrypt_hash (byte string, bytearray):
  439. The reference bcrypt hash the password needs to be checked against.
  440. Raises:
  441. ValueError: if the password does not match
  442. """
  443. bcrypt_hash = tobytes(bcrypt_hash)
  444. if len(bcrypt_hash) != 60:
  445. raise ValueError("Incorrect length of the bcrypt hash: %d bytes instead of 60" % len(bcrypt_hash))
  446. if bcrypt_hash[:4] != b'$2a$':
  447. raise ValueError("Unsupported prefix")
  448. p = re.compile(br'\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})')
  449. r = p.match(bcrypt_hash)
  450. if not r:
  451. raise ValueError("Incorrect bcrypt hash format")
  452. cost = int(r.group(1))
  453. if not (4 <= cost <= 31):
  454. raise ValueError("Incorrect cost")
  455. salt = _bcrypt_decode(r.group(2))
  456. bcrypt_hash2 = bcrypt(password, cost, salt)
  457. secret = get_random_bytes(16)
  458. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash).digest()
  459. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest()
  460. if mac1 != mac2:
  461. raise ValueError("Incorrect bcrypt hash")
  462. def SP800_108_Counter(master, key_len, prf, num_keys=None, label=b'', context=b''):
  463. """Derive one or more keys from a master secret using
  464. a pseudorandom function in Counter Mode, as specified in
  465. `NIST SP 800-108r1 <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-108r1.pdf>`_.
  466. Args:
  467. master (byte string):
  468. The secret value used by the KDF to derive the other keys.
  469. It must not be a password.
  470. The length on the secret must be consistent with the input expected by
  471. the :data:`prf` function.
  472. key_len (integer):
  473. The length in bytes of each derived key.
  474. prf (function):
  475. A pseudorandom function that takes two byte strings as parameters:
  476. the secret and an input. It returns another byte string.
  477. num_keys (integer):
  478. The number of keys to derive. Every key is :data:`key_len` bytes long.
  479. By default, only 1 key is derived.
  480. label (byte string):
  481. Optional description of the purpose of the derived keys.
  482. It must not contain zero bytes.
  483. context (byte string):
  484. Optional information pertaining to
  485. the protocol that uses the keys, such as the identity of the
  486. participants, nonces, session IDs, etc.
  487. It must not contain zero bytes.
  488. Return:
  489. - a byte string (if ``num_keys`` is not specified), or
  490. - a tuple of byte strings (if ``num_key`` is specified).
  491. """
  492. if num_keys is None:
  493. num_keys = 1
  494. if label.find(b'\x00') != -1:
  495. raise ValueError("Null byte found in label")
  496. if context.find(b'\x00') != -1:
  497. raise ValueError("Null byte found in context")
  498. key_len_enc = long_to_bytes(key_len * num_keys * 8, 4)
  499. output_len = key_len * num_keys
  500. i = 1
  501. dk = b""
  502. while len(dk) < output_len:
  503. info = long_to_bytes(i, 4) + label + b'\x00' + context + key_len_enc
  504. dk += prf(master, info)
  505. i += 1
  506. if i > 0xFFFFFFFF:
  507. raise ValueError("Overflow in SP800 108 counter")
  508. if num_keys == 1:
  509. return dk[:key_len]
  510. else:
  511. kol = [dk[idx:idx + key_len]
  512. for idx in iter_range(0, output_len, key_len)]
  513. return kol