Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py: 81%

27 statements  

« prev     ^ index     » next       coverage.py v7.2.1, created at 2023-03-14 06:36 +0000

1# This file is dual licensed under the terms of the Apache License, Version 

2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 

3# for complete details. 

4 

5 

6import typing 

7 

8from cryptography import utils 

9from cryptography.exceptions import ( 

10 AlreadyFinalized, 

11 InvalidKey, 

12 UnsupportedAlgorithm, 

13 _Reasons, 

14) 

15from cryptography.hazmat.primitives import constant_time, hashes 

16from cryptography.hazmat.primitives.kdf import KeyDerivationFunction 

17 

18 

19class PBKDF2HMAC(KeyDerivationFunction): 

20 def __init__( 

21 self, 

22 algorithm: hashes.HashAlgorithm, 

23 length: int, 

24 salt: bytes, 

25 iterations: int, 

26 backend: typing.Any = None, 

27 ): 

28 from cryptography.hazmat.backends.openssl.backend import ( 

29 backend as ossl, 

30 ) 

31 

32 if not ossl.pbkdf2_hmac_supported(algorithm): 

33 raise UnsupportedAlgorithm( 

34 "{} is not supported for PBKDF2 by this backend.".format( 

35 algorithm.name 

36 ), 

37 _Reasons.UNSUPPORTED_HASH, 

38 ) 

39 self._used = False 

40 self._algorithm = algorithm 

41 self._length = length 

42 utils._check_bytes("salt", salt) 

43 self._salt = salt 

44 self._iterations = iterations 

45 

46 def derive(self, key_material: bytes) -> bytes: 

47 if self._used: 

48 raise AlreadyFinalized("PBKDF2 instances can only be used once.") 

49 self._used = True 

50 

51 utils._check_byteslike("key_material", key_material) 

52 from cryptography.hazmat.backends.openssl.backend import backend 

53 

54 return backend.derive_pbkdf2_hmac( 

55 self._algorithm, 

56 self._length, 

57 self._salt, 

58 self._iterations, 

59 key_material, 

60 ) 

61 

62 def verify(self, key_material: bytes, expected_key: bytes) -> None: 

63 derived_key = self.derive(key_material) 

64 if not constant_time.bytes_eq(derived_key, expected_key): 

65 raise InvalidKey("Keys do not match.")