scrypt.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. import sys
  5. import typing
  6. from cryptography import utils
  7. from cryptography.exceptions import (
  8. AlreadyFinalized,
  9. InvalidKey,
  10. UnsupportedAlgorithm,
  11. _Reasons,
  12. )
  13. from cryptography.hazmat.backends import _get_backend
  14. from cryptography.hazmat.backends.interfaces import Backend, ScryptBackend
  15. from cryptography.hazmat.primitives import constant_time
  16. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  17. # This is used by the scrypt tests to skip tests that require more memory
  18. # than the MEM_LIMIT
  19. _MEM_LIMIT = sys.maxsize // 2
  20. class Scrypt(KeyDerivationFunction):
  21. def __init__(
  22. self,
  23. salt: bytes,
  24. length: int,
  25. n: int,
  26. r: int,
  27. p: int,
  28. backend: typing.Optional[Backend] = None,
  29. ):
  30. backend = _get_backend(backend)
  31. if not isinstance(backend, ScryptBackend):
  32. raise UnsupportedAlgorithm(
  33. "Backend object does not implement ScryptBackend.",
  34. _Reasons.BACKEND_MISSING_INTERFACE,
  35. )
  36. self._length = length
  37. utils._check_bytes("salt", salt)
  38. if n < 2 or (n & (n - 1)) != 0:
  39. raise ValueError("n must be greater than 1 and be a power of 2.")
  40. if r < 1:
  41. raise ValueError("r must be greater than or equal to 1.")
  42. if p < 1:
  43. raise ValueError("p must be greater than or equal to 1.")
  44. self._used = False
  45. self._salt = salt
  46. self._n = n
  47. self._r = r
  48. self._p = p
  49. self._backend = backend
  50. def derive(self, key_material: bytes) -> bytes:
  51. if self._used:
  52. raise AlreadyFinalized("Scrypt instances can only be used once.")
  53. self._used = True
  54. utils._check_byteslike("key_material", key_material)
  55. return self._backend.derive_scrypt(
  56. key_material, self._salt, self._length, self._n, self._r, self._p
  57. )
  58. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  59. derived_key = self.derive(key_material)
  60. if not constant_time.bytes_eq(derived_key, expected_key):
  61. raise InvalidKey("Keys do not match.")