diff --git a/docs/hazmat/primitives/key-derivation-functions.rst b/docs/hazmat/primitives/key-derivation-functions.rst index abd5a4aff22f..e67fb21c5b8b 100644 --- a/docs/hazmat/primitives/key-derivation-functions.rst +++ b/docs/hazmat/primitives/key-derivation-functions.rst @@ -1480,13 +1480,40 @@ Interface supplied password. :return: The new key. :raises cryptography.exceptions.AlreadyFinalized: This is raised when - :meth:`derive` or + :meth:`derive`, + :meth:`derive_into`, or :meth:`verify` is called more than once. This generates and returns a new key from the supplied key material. + .. method:: derive_into(key_material, buffer) + + .. versionadded:: 47.0.0 + + :param key_material: The input key material. Depending on what + key derivation function you are using this + could be either random bytes, or a user + supplied password. + :type key_material: :term:`bytes-like` + :param buffer: A writable buffer to write the derived key into. + :return int: the number of bytes written to the buffer. + :raises ValueError: This exception is raised if the buffer length does + not match the expected key length. + :raises TypeError: This exception is raised if ``key_material`` or + ``buffer`` is not ``bytes``. + :raises cryptography.exceptions.AlreadyFinalized: This is raised when + :meth:`derive`, + :meth:`derive_into`, or + :meth:`verify` is + called more than + once. + + This generates a new key from the supplied key material and writes it + directly into the provided buffer. This is useful when you want to + avoid allocating new memory for the derived key. + .. method:: verify(key_material, expected_key) :param bytes key_material: The input key material. This is the same as @@ -1498,7 +1525,8 @@ Interface derived key does not match the expected key. :raises cryptography.exceptions.AlreadyFinalized: This is raised when - :meth:`derive` or + :meth:`derive`, + :meth:`derive_into`, or :meth:`verify` is called more than once. diff --git a/src/cryptography/hazmat/primitives/kdf/__init__.py b/src/cryptography/hazmat/primitives/kdf/__init__.py index 79bb459f01ec..26c45bd78f18 100644 --- a/src/cryptography/hazmat/primitives/kdf/__init__.py +++ b/src/cryptography/hazmat/primitives/kdf/__init__.py @@ -6,6 +6,8 @@ import abc +from cryptography.utils import Buffer + class KeyDerivationFunction(metaclass=abc.ABCMeta): @abc.abstractmethod @@ -15,6 +17,13 @@ def derive(self, key_material: bytes) -> bytes: key material. """ + @abc.abstractmethod + def derive_into(self, key_material: bytes, buffer: Buffer) -> None: + """ + Deterministically generates a new key based on the existing key + material and stores it in the provided buffer. + """ + @abc.abstractmethod def verify(self, key_material: bytes, expected_key: bytes) -> None: """