KDF.py 20 KB

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