blob: 0f3d1afe07560436afef458c035026c8f779bc19 [file] [log] [blame]
Paul Kehrerb6d764c2014-01-27 22:32:11 -06001.. hazmat::
2
Alex Stapletonc5fffd32014-03-18 15:29:00 +00003Key derivation functions
Paul Kehrerb6d764c2014-01-27 22:32:11 -06004========================
5
Paul Kehrer48402ff2015-02-16 15:31:52 -06006.. module:: cryptography.hazmat.primitives.kdf
Paul Kehrerb6d764c2014-01-27 22:32:11 -06007
Paul Kehrer0b181182014-01-29 16:34:47 -06008Key derivation functions derive bytes suitable for cryptographic operations
9from passwords or other data sources using a pseudo-random function (PRF).
10Different KDFs are suitable for different tasks such as:
Paul Kehrer1cab1042014-01-29 14:30:11 -060011
Paul Kehrer0b181182014-01-29 16:34:47 -060012* Cryptographic key derivation
Paul Kehrer1cab1042014-01-29 14:30:11 -060013
14 Deriving a key suitable for use as input to an encryption algorithm.
15 Typically this means taking a password and running it through an algorithm
David Reidc0248b92014-01-30 15:23:33 -080016 such as :class:`~cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC` or
17 :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDF`.
Paul Kehrer1cab1042014-01-29 14:30:11 -060018 This process is typically known as `key stretching`_.
19
Paul Kehrer0b181182014-01-29 16:34:47 -060020* Password storage
Paul Kehrer1cab1042014-01-29 14:30:11 -060021
22 When storing passwords you want to use an algorithm that is computationally
23 intensive. Legitimate users will only need to compute it once (for example,
24 taking the user's password, running it through the KDF, then comparing it
25 to the stored value), while attackers will need to do it billions of times.
26 Ideal password storage KDFs will be demanding on both computational and
27 memory resources.
Paul Kehrerb6d764c2014-01-27 22:32:11 -060028
Paul Kehrer0b181182014-01-29 16:34:47 -060029.. currentmodule:: cryptography.hazmat.primitives.kdf.pbkdf2
30
31.. class:: PBKDF2HMAC(algorithm, length, salt, iterations, backend)
Paul Kehrerb6d764c2014-01-27 22:32:11 -060032
Paul Kehrer5d1af212014-01-28 12:19:32 -060033 .. versionadded:: 0.2
34
Paul Kehrer298e5332014-01-29 11:16:22 -060035 `PBKDF2`_ (Password Based Key Derivation Function 2) is typically used for
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060036 deriving a cryptographic key from a password. It may also be used for
Alex Gaynorc3a3ed42016-10-07 09:34:58 -050037 key storage, but an alternate key storage KDF such as
38 :class:`~cryptography.hazmat.primitives.kdf.scrypt.Scrypt` is generally
Paul Kehrer1cab1042014-01-29 14:30:11 -060039 considered a better solution.
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060040
Paul Kehrer5d1af212014-01-28 12:19:32 -060041 This class conforms to the
Paul Kehrer48402ff2015-02-16 15:31:52 -060042 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
Paul Kehrer5d1af212014-01-28 12:19:32 -060043 interface.
44
Paul Kehrerb6d764c2014-01-27 22:32:11 -060045 .. doctest::
46
Paul Kehrer5d1af212014-01-28 12:19:32 -060047 >>> import os
48 >>> from cryptography.hazmat.primitives import hashes
Paul Kehrerb3f763f2014-01-28 16:42:15 -060049 >>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
Paul Kehrerb6d764c2014-01-27 22:32:11 -060050 >>> from cryptography.hazmat.backends import default_backend
51 >>> backend = default_backend()
Cory Benfield9b22eb92017-05-22 22:40:40 -070052 >>> # Salts should be randomly generated
Paul Kehrerb6d764c2014-01-27 22:32:11 -060053 >>> salt = os.urandom(16)
54 >>> # derive
Paul Kehrerb3f763f2014-01-28 16:42:15 -060055 >>> kdf = PBKDF2HMAC(
56 ... algorithm=hashes.SHA256(),
57 ... length=32,
58 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060059 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060060 ... backend=backend
61 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060062 >>> key = kdf.derive(b"my great password")
63 >>> # verify
Paul Kehrerb3f763f2014-01-28 16:42:15 -060064 >>> kdf = PBKDF2HMAC(
65 ... algorithm=hashes.SHA256(),
66 ... length=32,
67 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060068 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060069 ... backend=backend
70 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060071 >>> kdf.verify(b"my great password", key)
Paul Kehrerb6d764c2014-01-27 22:32:11 -060072
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030073 :param algorithm: An instance of
74 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Paul Kehrera857fe62017-06-28 23:03:29 -050075 :param int length: The desired length of the derived key in bytes. Maximum
76 is (2\ :sup:`32` - 1) * ``algorithm.digest_size``.
Cory Benfield9b22eb92017-05-22 22:40:40 -070077 :param bytes salt: A salt. Secure values [#nist]_ are 128-bits (16 bytes)
78 or longer and randomly generated.
Paul Kehrer5d1af212014-01-28 12:19:32 -060079 :param int iterations: The number of iterations to perform of the hash
Paul Kehrerc58b4782014-01-29 13:56:25 -060080 function. This can be used to control the length of time the operation
81 takes. Higher numbers help mitigate brute force attacks against derived
82 keys. See OWASP's `Password Storage Cheat Sheet`_ for more
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060083 detailed recommendations if you intend to use this for password storage.
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030084 :param backend: An instance of
85 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`.
Paul Kehrerb6d764c2014-01-27 22:32:11 -060086
Alex Gaynor7a489db2014-03-22 15:09:34 -070087 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +080088 provided ``backend`` does not implement
89 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`
90
Ayrx00eff9c2014-05-17 19:47:09 +080091 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +080092
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060093 .. method:: derive(key_material)
94
Alex Gaynora8e125f2014-01-29 19:21:03 -080095 :param bytes key_material: The input key material. For PBKDF2 this
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060096 should be a password.
Paul Kehrer0b181182014-01-29 16:34:47 -060097 :return bytes: the derived key.
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060098 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
99 :meth:`derive` or
100 :meth:`verify` is
101 called more than
102 once.
103
Ayrx6d69eab2014-05-17 16:59:31 +0800104 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800105 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800106
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600107 This generates and returns a new key from the supplied password.
108
109 .. method:: verify(key_material, expected_key)
110
Alex Gaynora8e125f2014-01-29 19:21:03 -0800111 :param bytes key_material: The input key material. This is the same as
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600112 ``key_material`` in :meth:`derive`.
Alex Gaynora8e125f2014-01-29 19:21:03 -0800113 :param bytes expected_key: The expected result of deriving a new key,
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600114 this is the same as the return value of
115 :meth:`derive`.
116 :raises cryptography.exceptions.InvalidKey: This is raised when the
117 derived key does not match
118 the expected key.
119 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
120 :meth:`derive` or
121 :meth:`verify` is
122 called more than
123 once.
124
125 This checks whether deriving a new key from the supplied
126 ``key_material`` generates the same key as the ``expected_key``, and
127 raises an exception if they do not match. This can be used for
Paul Kehrer99d51902014-01-28 20:16:20 -0600128 checking whether the password a user provides matches the stored derived
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600129 key.
130
David Reidc0248b92014-01-30 15:23:33 -0800131
132.. currentmodule:: cryptography.hazmat.primitives.kdf.hkdf
133
134.. class:: HKDF(algorithm, length, salt, info, backend)
135
136 .. versionadded:: 0.2
137
David Reid2ad94ab2014-02-03 10:01:15 -0800138 `HKDF`_ (HMAC-based Extract-and-Expand Key Derivation Function) is suitable
David Reidc0248b92014-01-30 15:23:33 -0800139 for deriving keys of a fixed size used for other cryptographic operations.
Alex Gaynorc43bb752014-02-12 16:42:11 -0800140
141 .. warning::
142
143 HKDF should not be used for password storage.
David Reidc0248b92014-01-30 15:23:33 -0800144
David Reid5df929c2014-02-03 13:26:15 -0800145 .. doctest::
146
147 >>> import os
148 >>> from cryptography.hazmat.primitives import hashes
149 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
150 >>> from cryptography.hazmat.backends import default_backend
151 >>> backend = default_backend()
152 >>> salt = os.urandom(16)
153 >>> info = b"hkdf-example"
154 >>> hkdf = HKDF(
155 ... algorithm=hashes.SHA256(),
156 ... length=32,
157 ... salt=salt,
158 ... info=info,
159 ... backend=backend
160 ... )
David Reid134f1f42014-02-03 13:54:30 -0800161 >>> key = hkdf.derive(b"input key")
David Reid5df929c2014-02-03 13:26:15 -0800162 >>> hkdf = HKDF(
163 ... algorithm=hashes.SHA256(),
164 ... length=32,
165 ... salt=salt,
166 ... info=info,
167 ... backend=backend
168 ... )
169 >>> hkdf.verify(b"input key", key)
170
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300171 :param algorithm: An instance of
172 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
David Reidc0248b92014-01-30 15:23:33 -0800173
Paul Kehrera857fe62017-06-28 23:03:29 -0500174 :param int length: The desired length of the derived key in bytes. Maximum
175 is ``255 * (algorithm.digest_size // 8)``.
David Reidc0248b92014-01-30 15:23:33 -0800176
David Reid2ad94ab2014-02-03 10:01:15 -0800177 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
178 highly recommended. Ideally as many bits of entropy as the security
179 level of the hash: often that means cryptographically random and as
180 long as the hash output. Worse (shorter, less entropy) salt values can
181 still meaningfully contribute to security. May be reused. Does not have
182 to be secret, but may cause stronger security guarantees if secret; see
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400183 :rfc:`5869` and the `HKDF paper`_ for more details. If ``None`` is
David Reid2ad94ab2014-02-03 10:01:15 -0800184 explicitly passed a default salt of ``algorithm.digest_size // 8`` null
185 bytes will be used.
David Reidc0248b92014-01-30 15:23:33 -0800186
187 :param bytes info: Application specific context information. If ``None``
188 is explicitly passed an empty byte string will be used.
189
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300190 :param backend: An instance of
191 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
David Reidc0248b92014-01-30 15:23:33 -0800192
Alex Gaynor7a489db2014-03-22 15:09:34 -0700193 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +0800194 provided ``backend`` does not implement
195 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
196
Ayrx6d69eab2014-05-17 16:59:31 +0800197 :raises TypeError: This exception is raised if ``salt`` or ``info`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800198 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800199
David Reidc0248b92014-01-30 15:23:33 -0800200 .. method:: derive(key_material)
201
202 :param bytes key_material: The input key material.
Ayrx1534e092014-05-06 14:19:46 +0800203 :return bytes: The derived key.
Ayrx6d69eab2014-05-17 16:59:31 +0800204 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800205 ``bytes``.
David Reidc0248b92014-01-30 15:23:33 -0800206
207 Derives a new key from the input key material by performing both the
208 extract and expand operations.
209
210 .. method:: verify(key_material, expected_key)
211
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600212 :param bytes key_material: The input key material. This is the same as
David Reidc0248b92014-01-30 15:23:33 -0800213 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600214 :param bytes expected_key: The expected result of deriving a new key,
David Reidc0248b92014-01-30 15:23:33 -0800215 this is the same as the return value of
216 :meth:`derive`.
217 :raises cryptography.exceptions.InvalidKey: This is raised when the
218 derived key does not match
219 the expected key.
220 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
221 :meth:`derive` or
222 :meth:`verify` is
223 called more than
224 once.
225
226 This checks whether deriving a new key from the supplied
227 ``key_material`` generates the same key as the ``expected_key``, and
David Reidb9fa7712014-02-03 10:45:11 -0800228 raises an exception if they do not match.
David Reidc0248b92014-01-30 15:23:33 -0800229
Ayrx9d72f122014-05-06 20:27:51 +0800230
Ayrxc0ce9112014-05-07 16:22:09 +0800231.. class:: HKDFExpand(algorithm, length, info, backend)
Ayrx9d72f122014-05-06 20:27:51 +0800232
233 .. versionadded:: 0.5
234
235 HKDF consists of two stages, extract and expand. This class exposes an
236 expand only version of HKDF that is suitable when the key material is
237 already cryptographically strong.
238
239 .. warning::
240
Ayrxc0ce9112014-05-07 16:22:09 +0800241 HKDFExpand should only be used if the key material is
Ayrx9d72f122014-05-06 20:27:51 +0800242 cryptographically strong. You should use
243 :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDF` if
244 you are unsure.
245
246 .. doctest::
247
248 >>> import os
249 >>> from cryptography.hazmat.primitives import hashes
Ayrxc0ce9112014-05-07 16:22:09 +0800250 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
Ayrx9d72f122014-05-06 20:27:51 +0800251 >>> from cryptography.hazmat.backends import default_backend
252 >>> backend = default_backend()
253 >>> info = b"hkdf-example"
254 >>> key_material = os.urandom(16)
Ayrxc0ce9112014-05-07 16:22:09 +0800255 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800256 ... algorithm=hashes.SHA256(),
257 ... length=32,
258 ... info=info,
259 ... backend=backend
260 ... )
261 >>> key = hkdf.derive(key_material)
Ayrxc0ce9112014-05-07 16:22:09 +0800262 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800263 ... algorithm=hashes.SHA256(),
264 ... length=32,
265 ... info=info,
266 ... backend=backend
267 ... )
268 >>> hkdf.verify(key_material, key)
269
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300270 :param algorithm: An instance of
271 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Ayrx9d72f122014-05-06 20:27:51 +0800272
Paul Kehrera857fe62017-06-28 23:03:29 -0500273 :param int length: The desired length of the derived key in bytes. Maximum
274 is ``255 * (algorithm.digest_size // 8)``.
Ayrx9d72f122014-05-06 20:27:51 +0800275
276 :param bytes info: Application specific context information. If ``None``
277 is explicitly passed an empty byte string will be used.
278
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300279 :param backend: An instance of
280 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Ayrx9d72f122014-05-06 20:27:51 +0800281
282 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
283 provided ``backend`` does not implement
284 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
Ayrx00eff9c2014-05-17 19:47:09 +0800285 :raises TypeError: This exception is raised if ``info`` is not ``bytes``.
Ayrx9d72f122014-05-06 20:27:51 +0800286
287 .. method:: derive(key_material)
288
289 :param bytes key_material: The input key material.
290 :return bytes: The derived key.
291
Ayrx6d69eab2014-05-17 16:59:31 +0800292 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800293 ``bytes``.
Ayrxc48100a2014-05-10 13:01:46 +0800294
Ayrx9d72f122014-05-06 20:27:51 +0800295 Derives a new key from the input key material by performing both the
296 extract and expand operations.
297
298 .. method:: verify(key_material, expected_key)
299
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600300 :param bytes key_material: The input key material. This is the same as
Ayrx9d72f122014-05-06 20:27:51 +0800301 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600302 :param bytes expected_key: The expected result of deriving a new key,
Ayrx9d72f122014-05-06 20:27:51 +0800303 this is the same as the return value of
304 :meth:`derive`.
305 :raises cryptography.exceptions.InvalidKey: This is raised when the
306 derived key does not match
307 the expected key.
308 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
309 :meth:`derive` or
310 :meth:`verify` is
311 called more than
312 once.
Ayrxc48100a2014-05-10 13:01:46 +0800313 :raises TypeError: This is raised if the provided ``key_material`` is
Alex Gaynor617825d2018-05-12 14:33:20 -0400314 a ``unicode`` object
Ayrx9d72f122014-05-06 20:27:51 +0800315
316 This checks whether deriving a new key from the supplied
317 ``key_material`` generates the same key as the ``expected_key``, and
318 raises an exception if they do not match.
319
Simo Sorce8a690fb2015-05-01 15:56:30 -0400320.. currentmodule:: cryptography.hazmat.primitives.kdf.concatkdf
321
322.. class:: ConcatKDFHash(algorithm, length, otherinfo, backend)
323
324 .. versionadded:: 1.0
325
326 ConcatKDFHash (Concatenation Key Derivation Function) is defined by the
327 NIST Special Publication `NIST SP 800-56Ar2`_ document, to be used to
328 derive keys for use after a Key Exchange negotiation operation.
329
330 .. warning::
331
332 ConcatKDFHash should not be used for password storage.
333
334 .. doctest::
335
336 >>> import os
337 >>> from cryptography.hazmat.primitives import hashes
338 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
339 >>> from cryptography.hazmat.backends import default_backend
340 >>> backend = default_backend()
Simo Sorce8a690fb2015-05-01 15:56:30 -0400341 >>> otherinfo = b"concatkdf-example"
342 >>> ckdf = ConcatKDFHash(
343 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500344 ... length=32,
Simo Sorce8a690fb2015-05-01 15:56:30 -0400345 ... otherinfo=otherinfo,
346 ... backend=backend
347 ... )
348 >>> key = ckdf.derive(b"input key")
349 >>> ckdf = ConcatKDFHash(
350 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500351 ... length=32,
Simo Sorce8a690fb2015-05-01 15:56:30 -0400352 ... otherinfo=otherinfo,
353 ... backend=backend
354 ... )
355 >>> ckdf.verify(b"input key", key)
356
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300357 :param algorithm: An instance of
358 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400359
360 :param int length: The desired length of the derived key in bytes.
361 Maximum is ``hashlen * (2^32 -1)``.
362
363 :param bytes otherinfo: Application specific context information.
364 If ``None`` is explicitly passed an empty byte string will be used.
365
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300366 :param backend: An instance of
367 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400368
369 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
370 if the provided ``backend`` does not implement
371 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
372
373 :raises TypeError: This exception is raised if ``otherinfo`` is not
374 ``bytes``.
375
376 .. method:: derive(key_material)
377
378 :param bytes key_material: The input key material.
379 :return bytes: The derived key.
380 :raises TypeError: This exception is raised if ``key_material`` is
381 not ``bytes``.
382
Terry Chiadae40762015-06-13 11:26:16 +0800383 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400384
385 .. method:: verify(key_material, expected_key)
386
387 :param bytes key_material: The input key material. This is the same as
388 ``key_material`` in :meth:`derive`.
389 :param bytes expected_key: The expected result of deriving a new key,
390 this is the same as the return value of
391 :meth:`derive`.
392 :raises cryptography.exceptions.InvalidKey: This is raised when the
393 derived key does not match
394 the expected key.
395 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
396 :meth:`derive` or
397 :meth:`verify` is
398 called more than
399 once.
400
401 This checks whether deriving a new key from the supplied
402 ``key_material`` generates the same key as the ``expected_key``, and
403 raises an exception if they do not match.
404
405
406.. class:: ConcatKDFHMAC(algorithm, length, salt, otherinfo, backend)
407
408 .. versionadded:: 1.0
409
410 Similar to ConcatKFDHash but uses an HMAC function instead.
411
412 .. warning::
413
414 ConcatKDFHMAC should not be used for password storage.
415
416 .. doctest::
417
418 >>> import os
419 >>> from cryptography.hazmat.primitives import hashes
420 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC
421 >>> from cryptography.hazmat.backends import default_backend
422 >>> backend = default_backend()
423 >>> salt = os.urandom(16)
424 >>> otherinfo = b"concatkdf-example"
425 >>> ckdf = ConcatKDFHMAC(
426 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500427 ... length=32,
Simo Sorce8a690fb2015-05-01 15:56:30 -0400428 ... salt=salt,
429 ... otherinfo=otherinfo,
430 ... backend=backend
431 ... )
432 >>> key = ckdf.derive(b"input key")
433 >>> ckdf = ConcatKDFHMAC(
434 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500435 ... length=32,
Simo Sorce8a690fb2015-05-01 15:56:30 -0400436 ... salt=salt,
437 ... otherinfo=otherinfo,
438 ... backend=backend
439 ... )
440 >>> ckdf.verify(b"input key", key)
441
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300442 :param algorithm: An instance of
443 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400444
445 :param int length: The desired length of the derived key in bytes. Maximum
446 is ``hashlen * (2^32 -1)``.
447
448 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
449 highly recommended. Ideally as many bits of entropy as the security
450 level of the hash: often that means cryptographically random and as
451 long as the hash output. Does not have to be secret, but may cause
452 stronger security guarantees if secret; If ``None`` is explicitly
453 passed a default salt of ``algorithm.block_size`` null bytes will be
454 used.
455
456 :param bytes otherinfo: Application specific context information.
457 If ``None`` is explicitly passed an empty byte string will be used.
458
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300459 :param backend: An instance of
460 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400461
462 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
463 provided ``backend`` does not implement
464 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
465
466 :raises TypeError: This exception is raised if ``salt`` or ``otherinfo``
467 is not ``bytes``.
468
469 .. method:: derive(key_material)
470
471 :param bytes key_material: The input key material.
472 :return bytes: The derived key.
473 :raises TypeError: This exception is raised if ``key_material`` is not
474 ``bytes``.
475
Terry Chiadae40762015-06-13 11:26:16 +0800476 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400477
478 .. method:: verify(key_material, expected_key)
479
480 :param bytes key_material: The input key material. This is the same as
481 ``key_material`` in :meth:`derive`.
482 :param bytes expected_key: The expected result of deriving a new key,
483 this is the same as the return value of
484 :meth:`derive`.
485 :raises cryptography.exceptions.InvalidKey: This is raised when the
486 derived key does not match
487 the expected key.
488 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
489 :meth:`derive` or
490 :meth:`verify` is
491 called more than
492 once.
493
494 This checks whether deriving a new key from the supplied
495 ``key_material`` generates the same key as the ``expected_key``, and
496 raises an exception if they do not match.
497
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400498.. currentmodule:: cryptography.hazmat.primitives.kdf.x963kdf
499
500.. class:: X963KDF(algorithm, length, otherinfo, backend)
501
502 .. versionadded:: 1.1
503
504 X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI
505 in the `ANSI X9.63:2001`_ document, to be used to derive keys for use
506 after a Key Exchange negotiation operation.
507
508 SECG in `SEC 1 v2.0`_ recommends that
509 :class:`~cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash` be
510 used for new projects. This KDF should only be used for backwards
Alex Gaynorace036d2015-09-24 20:23:08 -0400511 compatibility with pre-existing protocols.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400512
513
514 .. warning::
515
516 X963KDF should not be used for password storage.
517
518 .. doctest::
519
520 >>> import os
521 >>> from cryptography.hazmat.primitives import hashes
522 >>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
523 >>> from cryptography.hazmat.backends import default_backend
524 >>> backend = default_backend()
525 >>> sharedinfo = b"ANSI X9.63 Example"
526 >>> xkdf = X963KDF(
527 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500528 ... length=32,
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400529 ... sharedinfo=sharedinfo,
530 ... backend=backend
531 ... )
532 >>> key = xkdf.derive(b"input key")
533 >>> xkdf = X963KDF(
534 ... algorithm=hashes.SHA256(),
Paul Kehrera857fe62017-06-28 23:03:29 -0500535 ... length=32,
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400536 ... sharedinfo=sharedinfo,
537 ... backend=backend
538 ... )
539 >>> xkdf.verify(b"input key", key)
540
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300541 :param algorithm: An instance of
542 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400543
544 :param int length: The desired length of the derived key in bytes.
545 Maximum is ``hashlen * (2^32 -1)``.
546
547 :param bytes sharedinfo: Application specific context information.
548 If ``None`` is explicitly passed an empty byte string will be used.
549
550 :param backend: A cryptography backend
551 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300552 instance.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400553
554 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
555 if the provided ``backend`` does not implement
556 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
557
558 :raises TypeError: This exception is raised if ``sharedinfo`` is not
559 ``bytes``.
560
561 .. method:: derive(key_material)
562
563 :param bytes key_material: The input key material.
564 :return bytes: The derived key.
565 :raises TypeError: This exception is raised if ``key_material`` is
566 not ``bytes``.
567
568 Derives a new key from the input key material.
569
570 .. method:: verify(key_material, expected_key)
571
572 :param bytes key_material: The input key material. This is the same as
573 ``key_material`` in :meth:`derive`.
574 :param bytes expected_key: The expected result of deriving a new key,
575 this is the same as the return value of
576 :meth:`derive`.
577 :raises cryptography.exceptions.InvalidKey: This is raised when the
578 derived key does not match
579 the expected key.
580 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
581 :meth:`derive` or
582 :meth:`verify` is
583 called more than
584 once.
585
586 This checks whether deriving a new key from the supplied
587 ``key_material`` generates the same key as the ``expected_key``, and
588 raises an exception if they do not match.
589
Simo Sorce8a690fb2015-05-01 15:56:30 -0400590
Jared6d7fe002016-05-29 17:32:37 -0700591.. currentmodule:: cryptography.hazmat.primitives.kdf.kbkdf
592
593.. class:: KBKDFHMAC(algorithm, mode, length, rlen, llen, location,\
594 label, context, fixed, backend)
595
596 .. versionadded:: 1.4
597
598 KBKDF (Key Based Key Derivation Function) is defined by the
599 `NIST SP 800-108`_ document, to be used to derive additional
600 keys from a key that has been established through an automated
601 key-establishment scheme.
602
603 .. warning::
604
605 KBKDFHMAC should not be used for password storage.
606
607 .. doctest::
608
609 >>> import os
610 >>> from cryptography.hazmat.primitives import hashes
611 >>> from cryptography.hazmat.primitives.kdf.kbkdf import (
612 ... CounterLocation, KBKDFHMAC, Mode
613 ... )
614 >>> from cryptography.hazmat.backends import default_backend
615 >>> backend = default_backend()
616 >>> label = b"KBKDF HMAC Label"
617 >>> context = b"KBKDF HMAC Context"
618 >>> kdf = KBKDFHMAC(
619 ... algorithm=hashes.SHA256(),
620 ... mode=Mode.CounterMode,
Paul Kehrera857fe62017-06-28 23:03:29 -0500621 ... length=32,
Jared6d7fe002016-05-29 17:32:37 -0700622 ... rlen=4,
623 ... llen=4,
624 ... location=CounterLocation.BeforeFixed,
625 ... label=label,
626 ... context=context,
627 ... fixed=None,
628 ... backend=backend
629 ... )
630 >>> key = kdf.derive(b"input key")
631 >>> kdf = KBKDFHMAC(
632 ... algorithm=hashes.SHA256(),
633 ... mode=Mode.CounterMode,
Paul Kehrera857fe62017-06-28 23:03:29 -0500634 ... length=32,
Jared6d7fe002016-05-29 17:32:37 -0700635 ... rlen=4,
636 ... llen=4,
637 ... location=CounterLocation.BeforeFixed,
638 ... label=label,
639 ... context=context,
640 ... fixed=None,
641 ... backend=backend
642 ... )
643 >>> kdf.verify(b"input key", key)
644
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300645 :param algorithm: An instance of
646 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Jared6d7fe002016-05-29 17:32:37 -0700647
648 :param mode: The desired mode of the PRF. A value from the
649 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.Mode` enum.
650
651 :param int length: The desired length of the derived key in bytes.
652
653 :param int rlen: An integer that indicates the length of the binary
654 representation of the counter in bytes.
655
656 :param int llen: An integer that indicates the binary
657 representation of the ``length`` in bytes.
658
659 :param location: The desired location of the counter. A value from the
660 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation` enum.
661
662 :param bytes label: Application specific label information. If ``None``
663 is explicitly passed an empty byte string will be used.
664
665 :param bytes context: Application specific context information. If ``None``
666 is explicitly passed an empty byte string will be used.
667
668 :param bytes fixed: Instead of specifying ``label`` and ``context`` you
669 may supply your own fixed data. If ``fixed`` is specified, ``label``
670 and ``context`` is ignored.
671
672 :param backend: A cryptography backend
673 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300674 instance.
Jared6d7fe002016-05-29 17:32:37 -0700675
676 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
677 if the provided ``backend`` does not implement
678 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
679
680 :raises TypeError: This exception is raised if ``label`` or ``context``
681 is not ``bytes``. Also raised if ``rlen`` or ``llen`` is not ``int``.
682
683 :raises ValueError: This exception is raised if ``rlen`` or ``llen``
684 is greater than 4 or less than 1. This exception is also raised if
685 you specify a ``label`` or ``context`` and ``fixed``.
686
687 .. method:: derive(key_material)
688
689 :param bytes key_material: The input key material.
690 :return bytes: The derived key.
691 :raises TypeError: This exception is raised if ``key_material`` is
692 not ``bytes``.
693
694 Derives a new key from the input key material.
695
696 .. method:: verify(key_material, expected_key)
697
698 :param bytes key_material: The input key material. This is the same as
699 ``key_material`` in :meth:`derive`.
700 :param bytes expected_key: The expected result of deriving a new key,
701 this is the same as the return value of
702 :meth:`derive`.
703 :raises cryptography.exceptions.InvalidKey: This is raised when the
704 derived key does not match
705 the expected key.
706 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
707 :meth:`derive` or
708 :meth:`verify` is
709 called more than
710 once.
711
712 This checks whether deriving a new key from the supplied
713 ``key_material`` generates the same key as the ``expected_key``, and
714 raises an exception if they do not match.
715
716.. class:: Mode
717
718 An enumeration for the key based key derivative modes.
719
720 .. attribute:: CounterMode
721
722 The output of the PRF is computed with a counter
723 as the iteration variable.
724
725.. class:: CounterLocation
726
727 An enumeration for the key based key derivative counter location.
728
729 .. attribute:: BeforeFixed
730
731 The counter iteration variable will be concatenated before
732 the fixed input data.
733
734 .. attribute:: AfterFixed
735
736 The counter iteration variable will be concatenated after
737 the fixed input data.
738
Terry Chiad8a27df2016-09-01 23:39:57 +0800739.. currentmodule:: cryptography.hazmat.primitives.kdf.scrypt
740
741.. class:: Scrypt(salt, length, n, r, p, backend)
742
743 .. versionadded:: 1.6
744
745 Scrypt is a KDF designed for password storage by Colin Percival to be
746 resistant against hardware-assisted attackers by having a tunable memory
747 cost. It is described in :rfc:`7914`.
748
749 This class conforms to the
750 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
751 interface.
752
Paul Kehrerf12955c2017-06-07 02:20:33 -1000753 .. doctest::
Terry Chiad8a27df2016-09-01 23:39:57 +0800754
755 >>> import os
Terry Chiad8a27df2016-09-01 23:39:57 +0800756 >>> from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
757 >>> from cryptography.hazmat.backends import default_backend
758 >>> backend = default_backend()
759 >>> salt = os.urandom(16)
760 >>> # derive
761 >>> kdf = Scrypt(
762 ... salt=salt,
Paul Kehrera857fe62017-06-28 23:03:29 -0500763 ... length=32,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800764 ... n=2**14,
Terry Chiad8a27df2016-09-01 23:39:57 +0800765 ... r=8,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800766 ... p=1,
Terry Chiad8a27df2016-09-01 23:39:57 +0800767 ... backend=backend
768 ... )
769 >>> key = kdf.derive(b"my great password")
770 >>> # verify
771 >>> kdf = Scrypt(
772 ... salt=salt,
Paul Kehrera857fe62017-06-28 23:03:29 -0500773 ... length=32,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800774 ... n=2**14,
Terry Chiad8a27df2016-09-01 23:39:57 +0800775 ... r=8,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800776 ... p=1,
Terry Chiad8a27df2016-09-01 23:39:57 +0800777 ... backend=backend
778 ... )
779 >>> kdf.verify(b"my great password", key)
780
781 :param bytes salt: A salt.
Paul Kehrera857fe62017-06-28 23:03:29 -0500782 :param int length: The desired length of the derived key in bytes.
Terry Chiad8a27df2016-09-01 23:39:57 +0800783 :param int n: CPU/Memory cost parameter. It must be larger than 1 and be a
784 power of 2.
785 :param int r: Block size parameter.
786 :param int p: Parallelization parameter.
787
788 The computational and memory cost of Scrypt can be adjusted by manipulating
Nick Badgeracaf89d2016-12-10 17:41:50 -0800789 the 3 parameters: ``n``, ``r``, and ``p``. In general, the memory cost of
790 Scrypt is affected by the values of both ``n`` and ``r``, while ``n`` also
791 determines the number of iterations performed. ``p`` increases the
792 computational cost without affecting memory usage. A more in-depth
793 explanation of the 3 parameters can be found `here`_.
Terry Chiad8a27df2016-09-01 23:39:57 +0800794
Nick Badgeracaf89d2016-12-10 17:41:50 -0800795 :rfc:`7914` `recommends`_ values of ``r=8`` and ``p=1`` while scaling ``n``
796 to a number appropriate for your system. `The scrypt paper`_ suggests a
797 minimum value of ``n=2**14`` for interactive logins (t < 100ms), or
798 ``n=2**20`` for more sensitive files (t < 5s).
Terry Chiad8a27df2016-09-01 23:39:57 +0800799
800 :param backend: An instance of
801 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`.
802
803 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
804 provided ``backend`` does not implement
805 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`
806
807 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Terry Chiaa2d0da92016-09-03 07:57:45 +0800808 :raises ValueError: This exception is raised if ``n`` is less than 2, if
809 ``n`` is not a power of 2, if ``r`` is less than 1 or if ``p`` is less
810 than 1.
Terry Chiad8a27df2016-09-01 23:39:57 +0800811
812 .. method:: derive(key_material)
813
814 :param bytes key_material: The input key material.
815 :return bytes: the derived key.
816 :raises TypeError: This exception is raised if ``key_material`` is not
817 ``bytes``.
818 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
819 :meth:`derive` or
820 :meth:`verify` is
821 called more than
822 once.
823
824 This generates and returns a new key from the supplied password.
825
826 .. method:: verify(key_material, expected_key)
827
828 :param bytes key_material: The input key material. This is the same as
829 ``key_material`` in :meth:`derive`.
830 :param bytes expected_key: The expected result of deriving a new key,
831 this is the same as the return value of
832 :meth:`derive`.
833 :raises cryptography.exceptions.InvalidKey: This is raised when the
834 derived key does not match
835 the expected key.
836 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
837 :meth:`derive` or
838 :meth:`verify` is
839 called more than
840 once.
841
842 This checks whether deriving a new key from the supplied
843 ``key_material`` generates the same key as the ``expected_key``, and
844 raises an exception if they do not match. This can be used for
845 checking whether the password a user provides matches the stored derived
846 key.
847
Paul Kehrer48402ff2015-02-16 15:31:52 -0600848Interface
849~~~~~~~~~
850
851.. currentmodule:: cryptography.hazmat.primitives.kdf
852
853.. class:: KeyDerivationFunction
854
855 .. versionadded:: 0.2
856
857 .. method:: derive(key_material)
858
859 :param bytes key_material: The input key material. Depending on what
860 key derivation function you are using this
861 could be either random bytes, or a user
862 supplied password.
863 :return: The new key.
864 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
865 :meth:`derive` or
866 :meth:`verify` is
867 called more than
868 once.
869
870 This generates and returns a new key from the supplied key material.
871
872 .. method:: verify(key_material, expected_key)
873
874 :param bytes key_material: The input key material. This is the same as
875 ``key_material`` in :meth:`derive`.
876 :param bytes expected_key: The expected result of deriving a new key,
877 this is the same as the return value of
878 :meth:`derive`.
879 :raises cryptography.exceptions.InvalidKey: This is raised when the
880 derived key does not match
881 the expected key.
882 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
883 :meth:`derive` or
884 :meth:`verify` is
885 called more than
886 once.
887
888 This checks whether deriving a new key from the supplied
889 ``key_material`` generates the same key as the ``expected_key``, and
890 raises an exception if they do not match. This can be used for
891 something like checking whether a user's password attempt matches the
892 stored derived key.
893
894
Cory Benfield9b22eb92017-05-22 22:40:40 -0700895.. [#nist] See `NIST SP 800-132`_.
896
Alex Gaynor53e45052017-09-20 09:57:47 -0400897.. _`NIST SP 800-132`: https://csrc.nist.gov/publications/detail/sp/800-132/final
898.. _`NIST SP 800-108`: https://csrc.nist.gov/publications/detail/sp/800-108/final
899.. _`NIST SP 800-56Ar2`: https://csrc.nist.gov/publications/detail/sp/800-56a/rev-2/final
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400900.. _`ANSI X9.63:2001`: https://webstore.ansi.org
901.. _`SEC 1 v2.0`: http://www.secg.org/sec1-v2.pdf
Paul Kehrerb3f763f2014-01-28 16:42:15 -0600902.. _`Password Storage Cheat Sheet`: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
David Reidb80deea2014-02-03 10:33:16 -0800903.. _`PBKDF2`: https://en.wikipedia.org/wiki/PBKDF2
David Reidb80deea2014-02-03 10:33:16 -0800904.. _`key stretching`: https://en.wikipedia.org/wiki/Key_stretching
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400905.. _`HKDF`: https://en.wikipedia.org/wiki/HKDF
David Reidb80deea2014-02-03 10:33:16 -0800906.. _`HKDF paper`: https://eprint.iacr.org/2010/264
Terry Chiad8a27df2016-09-01 23:39:57 +0800907.. _`here`: https://stackoverflow.com/a/30308723/1170681
908.. _`recommends`: https://tools.ietf.org/html/rfc7914#section-2
Nick Badgeracaf89d2016-12-10 17:41:50 -0800909.. _`The scrypt paper`: https://www.tarsnap.com/scrypt/scrypt.pdf