Danger
This is a “Hazardous Materials” module. You should ONLY use it if you’re100% absolutely sure that you know what you’re doing because this module isfull of land mines, dragons, and dinosaurs with laser guns.
Key derivation functions derive bytes suitable for cryptographic operationsfrom passwords or other data sources using a pseudo-random function (PRF).Different KDFs are suitable for different tasks such as:
Cryptographic key derivation
Deriving a key suitable for use as input to an encryption algorithm.Typically this means taking a password and running it through an algorithmsuch as PBKDF2HMAC orHKDF.This process is typically known as key stretching.
Password storage
When storing passwords you want to use an algorithm that is computationallyintensive. Legitimate users will only need to compute it once (for example,taking the user’s password, running it through the KDF, then comparing itto the stored value), while attackers will need to do it billions of times.Ideal password storage KDFs will be demanding on both computational andmemory resources.
Variable cost algorithms
PBKDF2
- class cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC(algorithm, length, salt, iterations)[source]
New in version 0.2.
PBKDF2 (Password Based Key Derivation Function 2) is typically used forderiving a cryptographic key from a password. It may also be used forkey storage, but an alternate key storage KDF such asScrypt is generallyconsidered a better solution.
This class conforms to theKeyDerivationFunctioninterface.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC>>> # Salts should be randomly generated>>> salt = os.urandom(16)>>> # derive>>> kdf = PBKDF2HMAC(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... iterations=480000,... )>>> key = kdf.derive(b"my great password")>>> # verify>>> kdf = PBKDF2HMAC(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... iterations=480000,... )>>> kdf.verify(b"my great password", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes. Maximumis (232 - 1) *
algorithm.digest_size
.salt (bytes) – A salt. Secure values [1] are 128-bits (16 bytes)or longer and randomly generated.
iterations (int) – The number of iterations to perform of the hashfunction. This can be used to control the length of time the operationtakes. Higher numbers help mitigate brute force attacks against derivedkeys. A more detailed description can be consulted for additionalinformation.
- Raises:
TypeError – This exception is raised if
salt
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material. For PBKDF2 thisshould be a password.
- Return bytes:
the derived key.
- Raises:
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
TypeError – This exception is raised if
key_material
is notbytes
.
This generates and returns a new key from the supplied password.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match. This can be used forchecking whether the password a user provides matches the stored derivedkey.
Scrypt
- class cryptography.hazmat.primitives.kdf.scrypt.Scrypt(salt, length, n, r, p)[source]
New in version 1.6.
Scrypt is a KDF designed for password storage by Colin Percival to beresistant against hardware-assisted attackers by having a tunable memorycost. It is described in RFC 7914.
This class conforms to theKeyDerivationFunctioninterface.
>>> import os>>> from cryptography.hazmat.primitives.kdf.scrypt import Scrypt>>> salt = os.urandom(16)>>> # derive>>> kdf = Scrypt(... salt=salt,... length=32,... n=2**14,... r=8,... p=1,... )>>> key = kdf.derive(b"my great password")>>> # verify>>> kdf = Scrypt(... salt=salt,... length=32,... n=2**14,... r=8,... p=1,... )>>> kdf.verify(b"my great password", key)
- Parameters:
The computational and memory cost of Scrypt can be adjusted by manipulatingthe 3 parameters:
n
,r
, andp
. In general, the memory cost ofScrypt is affected by the values of bothn
andr
, whilen
alsodetermines the number of iterations performed.p
increases thecomputational cost without affecting memory usage. A more in-depthexplanation of the 3 parameters can be found here.RFC 7914 recommends values of
r=8
andp=1
while scalingn
to a number appropriate for your system. The scrypt paper suggests aminimum value ofn=2**14
for interactive logins (t < 100ms), orn=2**20
for more sensitive files (t < 5s).- Raises:
cryptography.exceptions.UnsupportedAlgorithm – If Scrypt is notsupported by the OpenSSL version
cryptography
is using.TypeError – This exception is raised if
salt
is notbytes
.ValueError – This exception is raised if
n
is less than 2, ifn
is not a power of 2, ifr
is less than 1 or ifp
is lessthan 1.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
the derived key.
- Raises:
TypeError – This exception is raised if
key_material
is notbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This generates and returns a new key from the supplied password.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match. This can be used forchecking whether the password a user provides matches the stored derivedkey.
Fixed cost algorithms
ConcatKDF
- class cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash(algorithm, length, otherinfo)[source]
New in version 1.0.
ConcatKDFHash (Concatenation Key Derivation Function) is defined by theNIST Special Publication NIST SP 800-56Ar3 document, to be used toderive keys for use after a Key Exchange negotiation operation.
Warning
ConcatKDFHash should not be used for password storage.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash>>> otherinfo = b"concatkdf-example">>> ckdf = ConcatKDFHash(... algorithm=hashes.SHA256(),... length=32,... otherinfo=otherinfo,... )>>> key = ckdf.derive(b"input key")>>> ckdf = ConcatKDFHash(... algorithm=hashes.SHA256(),... length=32,... otherinfo=otherinfo,... )>>> ckdf.verify(b"input key", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes.Maximum is
hashlen * (2^32 -1)
.otherinfo (bytes) – Application specific context information.If
None
is explicitly passed an empty byte string will be used.
- Raises:
TypeError – This exception is raised if
otherinfo
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
isnotbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
- class cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHMAC(algorithm, length, salt, otherinfo)[source]
New in version 1.0.
Similar to ConcatKFDHash but uses an HMAC function instead.
Warning
ConcatKDFHMAC should not be used for password storage.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC>>> salt = os.urandom(16)>>> otherinfo = b"concatkdf-example">>> ckdf = ConcatKDFHMAC(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... otherinfo=otherinfo,... )>>> key = ckdf.derive(b"input key")>>> ckdf = ConcatKDFHMAC(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... otherinfo=otherinfo,... )>>> ckdf.verify(b"input key", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes. Maximumis
hashlen * (2^32 -1)
.salt (bytes) – A salt. Randomizes the KDF’s output. Optional, buthighly recommended. Ideally as many bits of entropy as the securitylevel of the hash: often that means cryptographically random and aslong as the hash output. Does not have to be secret, but may causestronger security guarantees if secret; If
None
is explicitlypassed a default salt ofalgorithm.block_size
null bytes will beused.otherinfo (bytes) – Application specific context information.If
None
is explicitly passed an empty byte string will be used.
- Raises:
TypeError – This exception is raised if
salt
orotherinfo
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
is notbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
HKDF
- class cryptography.hazmat.primitives.kdf.hkdf.HKDF(algorithm, length, salt, info)[source]
New in version 0.2.
HKDF (HMAC-based Extract-and-Expand Key Derivation Function) is suitablefor deriving keys of a fixed size used for other cryptographic operations.
Warning
HKDF should not be used for password storage.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF>>> salt = os.urandom(16)>>> info = b"hkdf-example">>> hkdf = HKDF(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... info=info,... )>>> key = hkdf.derive(b"input key")>>> hkdf = HKDF(... algorithm=hashes.SHA256(),... length=32,... salt=salt,... info=info,... )>>> hkdf.verify(b"input key", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes. Maximumis
255 * (algorithm.digest_size // 8)
.salt (bytes) – A salt. Randomizes the KDF’s output. Optional, buthighly recommended. Ideally as many bits of entropy as the securitylevel of the hash: often that means cryptographically random and aslong as the hash output. Worse (shorter, less entropy) salt values canstill meaningfully contribute to security. May be reused. Does not haveto be secret, but may cause stronger security guarantees if secret; seeRFC 5869 and the HKDF paper for more details. If
None
isexplicitly passed a default salt ofalgorithm.digest_size // 8
nullbytes will be used. See understanding HKDF for additional detail aboutthe salt and info parameters.info (bytes) – Application specific context information. If
None
is explicitly passed an empty byte string will be used.
- Raises:
TypeError – This exception is raised if
salt
orinfo
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
is notbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material by performing both theextract and expand operations.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
- class cryptography.hazmat.primitives.kdf.hkdf.HKDFExpand(algorithm, length, info)[source]
New in version 0.5.
HKDF consists of two stages, extract and expand. This class exposes anexpand only version of HKDF that is suitable when the key material isalready cryptographically strong.
Warning
HKDFExpand should only be used if the key material iscryptographically strong. You should useHKDF ifyou are unsure.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand>>> info = b"hkdf-example">>> key_material = os.urandom(16)>>> hkdf = HKDFExpand(... algorithm=hashes.SHA256(),... length=32,... info=info,... )>>> key = hkdf.derive(key_material)>>> hkdf = HKDFExpand(... algorithm=hashes.SHA256(),... length=32,... info=info,... )>>> hkdf.verify(key_material, key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes. Maximumis
255 * (algorithm.digest_size // 8)
.info (bytes) – Application specific context information. If
None
is explicitly passed an empty byte string will be used.
- Raises:
TypeError – This exception is raised if
info
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
is notbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material by performing both theextract and expand operations.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
TypeError – This is raised if the provided
key_material
isaunicode
object
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
KBKDF
- class cryptography.hazmat.primitives.kdf.kbkdf.KBKDFHMAC(algorithm, mode, length, rlen, llen, location, label, context, fixed)[source]
New in version 1.4.
KBKDF (Key Based Key Derivation Function) is defined by theNIST SP 800-108 document, to be used to derive additionalkeys from a key that has been established through an automatedkey-establishment scheme.
Warning
KBKDFHMAC should not be used for password storage.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.kbkdf import (... CounterLocation, KBKDFHMAC, Mode... )>>> label = b"KBKDF HMAC Label">>> context = b"KBKDF HMAC Context">>> kdf = KBKDFHMAC(... algorithm=hashes.SHA256(),... mode=Mode.CounterMode,... length=32,... rlen=4,... llen=4,... location=CounterLocation.BeforeFixed,... label=label,... context=context,... fixed=None,... )>>> key = kdf.derive(b"input key")>>> kdf = KBKDFHMAC(... algorithm=hashes.SHA256(),... mode=Mode.CounterMode,... length=32,... rlen=4,... llen=4,... location=CounterLocation.BeforeFixed,... label=label,... context=context,... fixed=None,... )>>> kdf.verify(b"input key", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.mode – The desired mode of the PRF. A value from theMode enum.
length (int) – The desired length of the derived key in bytes.
rlen (int) – An integer that indicates the length of the binaryrepresentation of the counter in bytes.
llen (int) – An integer that indicates the binaryrepresentation of the
length
in bytes.location – The desired location of the counter. A value from theCounterLocation enum.
label (bytes) – Application specific label information. If
None
is explicitly passed an empty byte string will be used.context (bytes) – Application specific context information. If
None
is explicitly passed an empty byte string will be used.fixed (bytes) – Instead of specifying
label
andcontext
youmay supply your own fixed data. Iffixed
is specified,label
andcontext
is ignored.break_location (int) – A keyword-only argument. An integer thatindicates the bytes offset where counter bytes are to be located.Required when
location
isMiddleFixed.
- Raises:
TypeError – This exception is raised if
label
orcontext
is notbytes
. Also raised ifrlen
,llen
, orbreak_location
is notint
.ValueError – This exception is raised if
rlen
orllen
is greater than 4 or less than 1. This exception is also raised ifyou specify alabel
orcontext
andfixed
. This exceptionis also raised if you specifybreak_location
andlocation
is notMiddleFixed.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
isnotbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
- class cryptography.hazmat.primitives.kdf.kbkdf.KBKDFCMAC(algorithm, mode, length, rlen, llen, location, label, context, fixed)[source]
New in version 35.0.0.
KBKDF (Key Based Key Derivation Function) is defined by theNIST SP 800-108 document, to be used to derive additionalkeys from a key that has been established through an automatedkey-establishment scheme.
Warning
KBKDFCMAC should not be used for password storage.
>>> from cryptography.hazmat.primitives.ciphers import algorithms>>> from cryptography.hazmat.primitives.kdf.kbkdf import (... CounterLocation, KBKDFCMAC, Mode... )>>> label = b"KBKDF CMAC Label">>> context = b"KBKDF CMAC Context">>> kdf = KBKDFCMAC(... algorithm=algorithms.AES,... mode=Mode.CounterMode,... length=32,... rlen=4,... llen=4,... location=CounterLocation.BeforeFixed,... label=label,... context=context,... fixed=None,... )>>> key = kdf.derive(b"32 bytes long input key material")>>> kdf = KBKDFCMAC(... algorithm=algorithms.AES,... mode=Mode.CounterMode,... length=32,... rlen=4,... llen=4,... location=CounterLocation.BeforeFixed,... label=label,... context=context,... fixed=None,... )>>> kdf.verify(b"32 bytes long input key material", key)
- Parameters:
algorithm – A class implementing a block cipher algorithm being asubclass of
CipherAlgorithm
andBlockCipherAlgorithm
.mode – The desired mode of the PRF. A value from theMode enum.
length (int) – The desired length of the derived key in bytes.
rlen (int) – An integer that indicates the length of the binaryrepresentation of the counter in bytes.
llen (int) – An integer that indicates the binaryrepresentation of the
length
in bytes.location – The desired location of the counter. A value from theCounterLocation enum.
label (bytes) – Application specific label information. If
None
is explicitly passed an empty byte string will be used.context (bytes) – Application specific context information. If
None
is explicitly passed an empty byte string will be used.fixed (bytes) – Instead of specifying
label
andcontext
youmay supply your own fixed data. Iffixed
is specified,label
andcontext
is ignored.break_location (int) – A keyword-only argument. An integer thatindicates the bytes offset where counter bytes are to be located.Required when
location
isMiddleFixed.
- Raises:
cryptography.exceptions.UnsupportedAlgorithm – This is raisedif
algorithm
is not a subclass ofCipherAlgorithm
andBlockCipherAlgorithm
.TypeError – This exception is raised if
label
orcontext
is notbytes
,rlen
,llen
, orbreak_location
is notint
,mode
is notMode orlocation
is notCounterLocation.ValueError – This exception is raised if
rlen
orllen
is greater than 4 or less than 1. This exception is also raised ifyou specify alabel
orcontext
andfixed
. This exceptionis also raised if you specifybreak_location
andlocation
is notMiddleFixed.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
isnotbytes
.ValueError – This exception is raised if
key_material
isnot a valid key foralgorithm
passed toKBKDFCMACconstructor.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
- Raises:
Exceptions raised by derive().
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
- class cryptography.hazmat.primitives.kdf.kbkdf.Mode[source]
An enumeration for the key based key derivative modes.
- CounterMode
The output of the PRF is computed with a counteras the iteration variable.
- class cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation[source]
An enumeration for the key based key derivative counter location.
- BeforeFixed
The counter iteration variable will be concatenated beforethe fixed input data.
- AfterFixed
The counter iteration variable will be concatenated afterthe fixed input data.
- MiddleFixed
New in version 38.0.0.
The counter iteration variable will be concatenated in the middleof the fixed input data.
X963KDF
- class cryptography.hazmat.primitives.kdf.x963kdf.X963KDF(algorithm, length, otherinfo)[source]
New in version 1.1.
X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSIin the ANSI X9.63:2001 document, to be used to derive keys for useafter a Key Exchange negotiation operation.
SECG in SEC 1 v2.0 recommends thatConcatKDFHash beused for new projects. This KDF should only be used for backwardscompatibility with pre-existing protocols.
Warning
X963KDF should not be used for password storage.
>>> import os>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF>>> sharedinfo = b"ANSI X9.63 Example">>> xkdf = X963KDF(... algorithm=hashes.SHA256(),... length=32,... sharedinfo=sharedinfo,... )>>> key = xkdf.derive(b"input key")>>> xkdf = X963KDF(... algorithm=hashes.SHA256(),... length=32,... sharedinfo=sharedinfo,... )>>> xkdf.verify(b"input key", key)
- Parameters:
algorithm – An instance of
HashAlgorithm
.length (int) – The desired length of the derived key in bytes.Maximum is
hashlen * (2^32 -1)
.sharedinfo (bytes) – Application specific context information.If
None
is explicitly passed an empty byte string will be used.
- Raises:
TypeError – This exception is raised if
sharedinfo
is notbytes
.
- derive(key_material)[source]
- Parameters:
key_material (bytes-like) – The input key material.
- Return bytes:
The derived key.
- Raises:
TypeError – This exception is raised if
key_material
isnotbytes
.cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
Derives a new key from the input key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match.
Interface
- class cryptography.hazmat.primitives.kdf.KeyDerivationFunction[source]
New in version 0.2.
- derive(key_material)[source]
- Parameters:
key_material (bytes) – The input key material. Depending on whatkey derivation function you are using thiscould be either random bytes, or a usersupplied password.
- Returns:
The new key.
- Raises:
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This generates and returns a new key from the supplied key material.
- verify(key_material, expected_key)[source]
- Parameters:
- Raises:
cryptography.exceptions.InvalidKey – This is raised when thederived key does not matchthe expected key.
cryptography.exceptions.AlreadyFinalized – This is raised whenderive() orverify() iscalled more thanonce.
This checks whether deriving a new key from the supplied
key_material
generates the same key as theexpected_key
, andraises an exception if they do not match. This can be used forsomething like checking whether a user’s password attempt matches thestored derived key.
I am an expert in cryptographic key derivation functions (KDFs) and related security concepts, backed by a deep understanding of the topic and hands-on experience in cryptography. The information provided here is not only theoretical but also practical, allowing users to implement and use these functions effectively.
The article discusses several key derivation functions used for various cryptographic purposes, emphasizing their suitability for specific tasks. Here's a breakdown of the concepts covered in the article:
-
Key Derivation Functions (KDFs):
- Key derivation functions generate bytes suitable for cryptographic operations from passwords or other data sources using a pseudo-random function (PRF).
- Different KDFs are suitable for various tasks, such as cryptographic key derivation and password storage.
-
Cryptographic Key Derivation:
- Involves deriving a key suitable for use as input to an encryption algorithm.
- Commonly achieved by running a password through algorithms like PBKDF2-HMAC or HKDF.
-
Password Storage:
- For secure password storage, computationally intensive algorithms are preferred.
- Legitimate users need to compute it once, while attackers need to perform computations billions of times.
-
Variable Cost Algorithms:
-
PBKDF2:
- PBKDF2 (Password Based Key Derivation Function 2) is used for deriving cryptographic keys from passwords.
- Parameters include algorithm, length, salt, and iterations.
- It is suitable for key stretching and password storage.
-
Scrypt:
- Scrypt is a KDF designed for password storage with tunable memory cost.
- Parameters include salt, length, n (CPU/Memory cost), r (block size), and p (parallelization).
- Memory and computational costs can be adjusted based on parameters.
-
-
Fixed Cost Algorithms:
-
ConcatKDF:
- Concatenation Key Derivation Function.
- It should not be used for password storage.
- Two variations: ConcatKDFHash and ConcatKDFHMAC.
-
HKDF:
- HMAC-based Extract-and-Expand Key Derivation Function.
- Suitable for deriving fixed-size keys for cryptographic operations.
- Parameters include algorithm, length, salt, and info.
-
KBKDF:
- Key Based Key Derivation Function.
- Defined by NIST SP 800-108 document.
- Two variations: KBKDFHMAC and KBKDFCMAC.
-
X963KDF:
- ANSI X9.63 Key Derivation Function.
- Defined by ANSI in the ANSI X9.63:2001 document.
-
-
Interface:
- The
KeyDerivationFunction
interface defines the common methodsderive
andverify
. - These methods generate and verify derived keys, providing a consistent interface for different KDFs.
- The
Overall, the article provides comprehensive information on various KDFs, their parameters, and best practices for their use in cryptographic applications.