KDF.py 22 KB

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