scrypt.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 annotations
  5. import sys
  6. import typing
  7. from cryptography import utils
  8. from cryptography.exceptions import (
  9. AlreadyFinalized,
  10. InvalidKey,
  11. UnsupportedAlgorithm,
  12. )
  13. from cryptography.hazmat.bindings._rust import openssl as rust_openssl
  14. from cryptography.hazmat.primitives import constant_time
  15. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  16. # This is used by the scrypt tests to skip tests that require more memory
  17. # than the MEM_LIMIT
  18. _MEM_LIMIT = sys.maxsize // 2
  19. class Scrypt(KeyDerivationFunction):
  20. def __init__(
  21. self,
  22. salt: bytes,
  23. length: int,
  24. n: int,
  25. r: int,
  26. p: int,
  27. backend: typing.Any = None,
  28. ):
  29. from cryptography.hazmat.backends.openssl.backend import (
  30. backend as ossl,
  31. )
  32. if not ossl.scrypt_supported():
  33. raise UnsupportedAlgorithm(
  34. "This version of OpenSSL does not support scrypt"
  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. def derive(self, key_material: bytes) -> bytes:
  50. if self._used:
  51. raise AlreadyFinalized("Scrypt instances can only be used once.")
  52. self._used = True
  53. utils._check_byteslike("key_material", key_material)
  54. return rust_openssl.kdf.derive_scrypt(
  55. key_material,
  56. self._salt,
  57. self._n,
  58. self._r,
  59. self._p,
  60. _MEM_LIMIT,
  61. self._length,
  62. )
  63. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  64. derived_key = self.derive(key_material)
  65. if not constant_time.bytes_eq(derived_key, expected_key):
  66. raise InvalidKey("Keys do not match.")