pbkdf2.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. from __future__ import absolute_import, division, print_function
  5. from cryptography import utils
  6. from cryptography.exceptions import (
  7. AlreadyFinalized,
  8. InvalidKey,
  9. UnsupportedAlgorithm,
  10. _Reasons,
  11. )
  12. from cryptography.hazmat.backends import _get_backend
  13. from cryptography.hazmat.backends.interfaces import PBKDF2HMACBackend
  14. from cryptography.hazmat.primitives import constant_time
  15. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  16. @utils.register_interface(KeyDerivationFunction)
  17. class PBKDF2HMAC(object):
  18. def __init__(self, algorithm, length, salt, iterations, backend=None):
  19. backend = _get_backend(backend)
  20. if not isinstance(backend, PBKDF2HMACBackend):
  21. raise UnsupportedAlgorithm(
  22. "Backend object does not implement PBKDF2HMACBackend.",
  23. _Reasons.BACKEND_MISSING_INTERFACE,
  24. )
  25. if not backend.pbkdf2_hmac_supported(algorithm):
  26. raise UnsupportedAlgorithm(
  27. "{} is not supported for PBKDF2 by this backend.".format(
  28. algorithm.name
  29. ),
  30. _Reasons.UNSUPPORTED_HASH,
  31. )
  32. self._used = False
  33. self._algorithm = algorithm
  34. self._length = length
  35. utils._check_bytes("salt", salt)
  36. self._salt = salt
  37. self._iterations = iterations
  38. self._backend = backend
  39. def derive(self, key_material):
  40. if self._used:
  41. raise AlreadyFinalized("PBKDF2 instances can only be used once.")
  42. self._used = True
  43. utils._check_byteslike("key_material", key_material)
  44. return self._backend.derive_pbkdf2_hmac(
  45. self._algorithm,
  46. self._length,
  47. self._salt,
  48. self._iterations,
  49. key_material,
  50. )
  51. def verify(self, key_material, expected_key):
  52. derived_key = self.derive(key_material)
  53. if not constant_time.bytes_eq(derived_key, expected_key):
  54. raise InvalidKey("Keys do not match.")