Debian Codegraph @

lib/Crypto/Protocol/KDF.py

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