blob: dbca3a5b6b1e50b1e97aa71070fd32aba098025a [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()
52 >>> salt = os.urandom(16)
53 >>> # derive
Paul Kehrerb3f763f2014-01-28 16:42:15 -060054 >>> kdf = PBKDF2HMAC(
55 ... algorithm=hashes.SHA256(),
56 ... length=32,
57 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060058 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060059 ... backend=backend
60 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060061 >>> key = kdf.derive(b"my great password")
62 >>> # verify
Paul Kehrerb3f763f2014-01-28 16:42:15 -060063 >>> kdf = PBKDF2HMAC(
64 ... algorithm=hashes.SHA256(),
65 ... length=32,
66 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060067 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060068 ... backend=backend
69 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060070 >>> kdf.verify(b"my great password", key)
Paul Kehrerb6d764c2014-01-27 22:32:11 -060071
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030072 :param algorithm: An instance of
73 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Paul Kehrer5d1af212014-01-28 12:19:32 -060074 :param int length: The desired length of the derived key. Maximum is
Paul Kehrerb3f763f2014-01-28 16:42:15 -060075 (2\ :sup:`32` - 1) * ``algorithm.digest_size``.
Paul Kehrer5d1af212014-01-28 12:19:32 -060076 :param bytes salt: A salt. `NIST SP 800-132`_ recommends 128-bits or
77 longer.
78 :param int iterations: The number of iterations to perform of the hash
Paul Kehrerc58b4782014-01-29 13:56:25 -060079 function. This can be used to control the length of time the operation
80 takes. Higher numbers help mitigate brute force attacks against derived
81 keys. See OWASP's `Password Storage Cheat Sheet`_ for more
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060082 detailed recommendations if you intend to use this for password storage.
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030083 :param backend: An instance of
84 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`.
Paul Kehrerb6d764c2014-01-27 22:32:11 -060085
Alex Gaynor7a489db2014-03-22 15:09:34 -070086 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +080087 provided ``backend`` does not implement
88 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`
89
Ayrx00eff9c2014-05-17 19:47:09 +080090 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +080091
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060092 .. method:: derive(key_material)
93
Alex Gaynora8e125f2014-01-29 19:21:03 -080094 :param bytes key_material: The input key material. For PBKDF2 this
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060095 should be a password.
Paul Kehrer0b181182014-01-29 16:34:47 -060096 :return bytes: the derived key.
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060097 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
98 :meth:`derive` or
99 :meth:`verify` is
100 called more than
101 once.
102
Ayrx6d69eab2014-05-17 16:59:31 +0800103 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800104 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800105
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600106 This generates and returns a new key from the supplied password.
107
108 .. method:: verify(key_material, expected_key)
109
Alex Gaynora8e125f2014-01-29 19:21:03 -0800110 :param bytes key_material: The input key material. This is the same as
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600111 ``key_material`` in :meth:`derive`.
Alex Gaynora8e125f2014-01-29 19:21:03 -0800112 :param bytes expected_key: The expected result of deriving a new key,
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600113 this is the same as the return value of
114 :meth:`derive`.
115 :raises cryptography.exceptions.InvalidKey: This is raised when the
116 derived key does not match
117 the expected key.
118 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
119 :meth:`derive` or
120 :meth:`verify` is
121 called more than
122 once.
123
124 This checks whether deriving a new key from the supplied
125 ``key_material`` generates the same key as the ``expected_key``, and
126 raises an exception if they do not match. This can be used for
Paul Kehrer99d51902014-01-28 20:16:20 -0600127 checking whether the password a user provides matches the stored derived
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600128 key.
129
David Reidc0248b92014-01-30 15:23:33 -0800130
131.. currentmodule:: cryptography.hazmat.primitives.kdf.hkdf
132
133.. class:: HKDF(algorithm, length, salt, info, backend)
134
135 .. versionadded:: 0.2
136
David Reid2ad94ab2014-02-03 10:01:15 -0800137 `HKDF`_ (HMAC-based Extract-and-Expand Key Derivation Function) is suitable
David Reidc0248b92014-01-30 15:23:33 -0800138 for deriving keys of a fixed size used for other cryptographic operations.
Alex Gaynorc43bb752014-02-12 16:42:11 -0800139
140 .. warning::
141
142 HKDF should not be used for password storage.
David Reidc0248b92014-01-30 15:23:33 -0800143
David Reid5df929c2014-02-03 13:26:15 -0800144 .. doctest::
145
146 >>> import os
147 >>> from cryptography.hazmat.primitives import hashes
148 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
149 >>> from cryptography.hazmat.backends import default_backend
150 >>> backend = default_backend()
151 >>> salt = os.urandom(16)
152 >>> info = b"hkdf-example"
153 >>> hkdf = HKDF(
154 ... algorithm=hashes.SHA256(),
155 ... length=32,
156 ... salt=salt,
157 ... info=info,
158 ... backend=backend
159 ... )
David Reid134f1f42014-02-03 13:54:30 -0800160 >>> key = hkdf.derive(b"input key")
David Reid5df929c2014-02-03 13:26:15 -0800161 >>> hkdf = HKDF(
162 ... algorithm=hashes.SHA256(),
163 ... length=32,
164 ... salt=salt,
165 ... info=info,
166 ... backend=backend
167 ... )
168 >>> hkdf.verify(b"input key", key)
169
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300170 :param algorithm: An instance of
171 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
David Reidc0248b92014-01-30 15:23:33 -0800172
173 :param int length: The desired length of the derived key. Maximum is
David Reidb89f34c2014-02-03 10:01:42 -0800174 ``255 * (algorithm.digest_size // 8)``.
David Reidc0248b92014-01-30 15:23:33 -0800175
David Reid2ad94ab2014-02-03 10:01:15 -0800176 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
177 highly recommended. Ideally as many bits of entropy as the security
178 level of the hash: often that means cryptographically random and as
179 long as the hash output. Worse (shorter, less entropy) salt values can
180 still meaningfully contribute to security. May be reused. Does not have
181 to be secret, but may cause stronger security guarantees if secret; see
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400182 :rfc:`5869` and the `HKDF paper`_ for more details. If ``None`` is
David Reid2ad94ab2014-02-03 10:01:15 -0800183 explicitly passed a default salt of ``algorithm.digest_size // 8`` null
184 bytes will be used.
David Reidc0248b92014-01-30 15:23:33 -0800185
186 :param bytes info: Application specific context information. If ``None``
187 is explicitly passed an empty byte string will be used.
188
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300189 :param backend: An instance of
190 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
David Reidc0248b92014-01-30 15:23:33 -0800191
Alex Gaynor7a489db2014-03-22 15:09:34 -0700192 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +0800193 provided ``backend`` does not implement
194 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
195
Ayrx6d69eab2014-05-17 16:59:31 +0800196 :raises TypeError: This exception is raised if ``salt`` or ``info`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800197 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800198
David Reidc0248b92014-01-30 15:23:33 -0800199 .. method:: derive(key_material)
200
201 :param bytes key_material: The input key material.
Ayrx1534e092014-05-06 14:19:46 +0800202 :return bytes: The derived key.
Ayrx6d69eab2014-05-17 16:59:31 +0800203 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800204 ``bytes``.
David Reidc0248b92014-01-30 15:23:33 -0800205
206 Derives a new key from the input key material by performing both the
207 extract and expand operations.
208
209 .. method:: verify(key_material, expected_key)
210
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600211 :param bytes key_material: The input key material. This is the same as
David Reidc0248b92014-01-30 15:23:33 -0800212 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600213 :param bytes expected_key: The expected result of deriving a new key,
David Reidc0248b92014-01-30 15:23:33 -0800214 this is the same as the return value of
215 :meth:`derive`.
216 :raises cryptography.exceptions.InvalidKey: This is raised when the
217 derived key does not match
218 the expected key.
219 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
220 :meth:`derive` or
221 :meth:`verify` is
222 called more than
223 once.
224
225 This checks whether deriving a new key from the supplied
226 ``key_material`` generates the same key as the ``expected_key``, and
David Reidb9fa7712014-02-03 10:45:11 -0800227 raises an exception if they do not match.
David Reidc0248b92014-01-30 15:23:33 -0800228
Ayrx9d72f122014-05-06 20:27:51 +0800229
Ayrxc0ce9112014-05-07 16:22:09 +0800230.. class:: HKDFExpand(algorithm, length, info, backend)
Ayrx9d72f122014-05-06 20:27:51 +0800231
232 .. versionadded:: 0.5
233
234 HKDF consists of two stages, extract and expand. This class exposes an
235 expand only version of HKDF that is suitable when the key material is
236 already cryptographically strong.
237
238 .. warning::
239
Ayrxc0ce9112014-05-07 16:22:09 +0800240 HKDFExpand should only be used if the key material is
Ayrx9d72f122014-05-06 20:27:51 +0800241 cryptographically strong. You should use
242 :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDF` if
243 you are unsure.
244
245 .. doctest::
246
247 >>> import os
248 >>> from cryptography.hazmat.primitives import hashes
Ayrxc0ce9112014-05-07 16:22:09 +0800249 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
Ayrx9d72f122014-05-06 20:27:51 +0800250 >>> from cryptography.hazmat.backends import default_backend
251 >>> backend = default_backend()
252 >>> info = b"hkdf-example"
253 >>> key_material = os.urandom(16)
Ayrxc0ce9112014-05-07 16:22:09 +0800254 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800255 ... algorithm=hashes.SHA256(),
256 ... length=32,
257 ... info=info,
258 ... backend=backend
259 ... )
260 >>> key = hkdf.derive(key_material)
Ayrxc0ce9112014-05-07 16:22:09 +0800261 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800262 ... algorithm=hashes.SHA256(),
263 ... length=32,
264 ... info=info,
265 ... backend=backend
266 ... )
267 >>> hkdf.verify(key_material, key)
268
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300269 :param algorithm: An instance of
270 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Ayrx9d72f122014-05-06 20:27:51 +0800271
272 :param int length: The desired length of the derived key. Maximum is
273 ``255 * (algorithm.digest_size // 8)``.
274
275 :param bytes info: Application specific context information. If ``None``
276 is explicitly passed an empty byte string will be used.
277
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300278 :param backend: An instance of
279 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Ayrx9d72f122014-05-06 20:27:51 +0800280
281 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
282 provided ``backend`` does not implement
283 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
Ayrxc48100a2014-05-10 13:01:46 +0800284 :raises TypeError: This is raised if the provided ``info`` is a unicode object
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
Ayrxc48100a2014-05-10 13:01:46 +0800292 :raises TypeError: This is raised if the provided ``key_material`` is
293 a unicode object
Ayrx6d69eab2014-05-17 16:59:31 +0800294 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800295 ``bytes``.
Ayrxc48100a2014-05-10 13:01:46 +0800296
Ayrx9d72f122014-05-06 20:27:51 +0800297 Derives a new key from the input key material by performing both the
298 extract and expand operations.
299
300 .. method:: verify(key_material, expected_key)
301
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600302 :param bytes key_material: The input key material. This is the same as
Ayrx9d72f122014-05-06 20:27:51 +0800303 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600304 :param bytes expected_key: The expected result of deriving a new key,
Ayrx9d72f122014-05-06 20:27:51 +0800305 this is the same as the return value of
306 :meth:`derive`.
307 :raises cryptography.exceptions.InvalidKey: This is raised when the
308 derived key does not match
309 the expected key.
310 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
311 :meth:`derive` or
312 :meth:`verify` is
313 called more than
314 once.
Ayrxc48100a2014-05-10 13:01:46 +0800315 :raises TypeError: This is raised if the provided ``key_material`` is
316 a unicode object
Ayrx9d72f122014-05-06 20:27:51 +0800317
318 This checks whether deriving a new key from the supplied
319 ``key_material`` generates the same key as the ``expected_key``, and
320 raises an exception if they do not match.
321
Simo Sorce8a690fb2015-05-01 15:56:30 -0400322.. currentmodule:: cryptography.hazmat.primitives.kdf.concatkdf
323
324.. class:: ConcatKDFHash(algorithm, length, otherinfo, backend)
325
326 .. versionadded:: 1.0
327
328 ConcatKDFHash (Concatenation Key Derivation Function) is defined by the
329 NIST Special Publication `NIST SP 800-56Ar2`_ document, to be used to
330 derive keys for use after a Key Exchange negotiation operation.
331
332 .. warning::
333
334 ConcatKDFHash should not be used for password storage.
335
336 .. doctest::
337
338 >>> import os
339 >>> from cryptography.hazmat.primitives import hashes
340 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
341 >>> from cryptography.hazmat.backends import default_backend
342 >>> backend = default_backend()
Simo Sorce8a690fb2015-05-01 15:56:30 -0400343 >>> otherinfo = b"concatkdf-example"
344 >>> ckdf = ConcatKDFHash(
345 ... algorithm=hashes.SHA256(),
346 ... length=256,
347 ... otherinfo=otherinfo,
348 ... backend=backend
349 ... )
350 >>> key = ckdf.derive(b"input key")
351 >>> ckdf = ConcatKDFHash(
352 ... algorithm=hashes.SHA256(),
353 ... length=256,
354 ... otherinfo=otherinfo,
355 ... backend=backend
356 ... )
357 >>> ckdf.verify(b"input key", key)
358
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300359 :param algorithm: An instance of
360 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400361
362 :param int length: The desired length of the derived key in bytes.
363 Maximum is ``hashlen * (2^32 -1)``.
364
365 :param bytes otherinfo: Application specific context information.
366 If ``None`` is explicitly passed an empty byte string will be used.
367
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300368 :param backend: An instance of
369 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400370
371 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
372 if the provided ``backend`` does not implement
373 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
374
375 :raises TypeError: This exception is raised if ``otherinfo`` is not
376 ``bytes``.
377
378 .. method:: derive(key_material)
379
380 :param bytes key_material: The input key material.
381 :return bytes: The derived key.
382 :raises TypeError: This exception is raised if ``key_material`` is
383 not ``bytes``.
384
Terry Chiadae40762015-06-13 11:26:16 +0800385 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400386
387 .. method:: verify(key_material, expected_key)
388
389 :param bytes key_material: The input key material. This is the same as
390 ``key_material`` in :meth:`derive`.
391 :param bytes expected_key: The expected result of deriving a new key,
392 this is the same as the return value of
393 :meth:`derive`.
394 :raises cryptography.exceptions.InvalidKey: This is raised when the
395 derived key does not match
396 the expected key.
397 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
398 :meth:`derive` or
399 :meth:`verify` is
400 called more than
401 once.
402
403 This checks whether deriving a new key from the supplied
404 ``key_material`` generates the same key as the ``expected_key``, and
405 raises an exception if they do not match.
406
407
408.. class:: ConcatKDFHMAC(algorithm, length, salt, otherinfo, backend)
409
410 .. versionadded:: 1.0
411
412 Similar to ConcatKFDHash but uses an HMAC function instead.
413
414 .. warning::
415
416 ConcatKDFHMAC should not be used for password storage.
417
418 .. doctest::
419
420 >>> import os
421 >>> from cryptography.hazmat.primitives import hashes
422 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC
423 >>> from cryptography.hazmat.backends import default_backend
424 >>> backend = default_backend()
425 >>> salt = os.urandom(16)
426 >>> otherinfo = b"concatkdf-example"
427 >>> ckdf = ConcatKDFHMAC(
428 ... algorithm=hashes.SHA256(),
429 ... length=256,
430 ... salt=salt,
431 ... otherinfo=otherinfo,
432 ... backend=backend
433 ... )
434 >>> key = ckdf.derive(b"input key")
435 >>> ckdf = ConcatKDFHMAC(
436 ... algorithm=hashes.SHA256(),
437 ... length=256,
438 ... salt=salt,
439 ... otherinfo=otherinfo,
440 ... backend=backend
441 ... )
442 >>> ckdf.verify(b"input key", key)
443
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300444 :param algorithm: An instance of
445 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400446
447 :param int length: The desired length of the derived key in bytes. Maximum
448 is ``hashlen * (2^32 -1)``.
449
450 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
451 highly recommended. Ideally as many bits of entropy as the security
452 level of the hash: often that means cryptographically random and as
453 long as the hash output. Does not have to be secret, but may cause
454 stronger security guarantees if secret; If ``None`` is explicitly
455 passed a default salt of ``algorithm.block_size`` null bytes will be
456 used.
457
458 :param bytes otherinfo: Application specific context information.
459 If ``None`` is explicitly passed an empty byte string will be used.
460
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300461 :param backend: An instance of
462 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400463
464 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
465 provided ``backend`` does not implement
466 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
467
468 :raises TypeError: This exception is raised if ``salt`` or ``otherinfo``
469 is not ``bytes``.
470
471 .. method:: derive(key_material)
472
473 :param bytes key_material: The input key material.
474 :return bytes: The derived key.
475 :raises TypeError: This exception is raised if ``key_material`` is not
476 ``bytes``.
477
Terry Chiadae40762015-06-13 11:26:16 +0800478 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400479
480 .. method:: verify(key_material, expected_key)
481
482 :param bytes key_material: The input key material. This is the same as
483 ``key_material`` in :meth:`derive`.
484 :param bytes expected_key: The expected result of deriving a new key,
485 this is the same as the return value of
486 :meth:`derive`.
487 :raises cryptography.exceptions.InvalidKey: This is raised when the
488 derived key does not match
489 the expected key.
490 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
491 :meth:`derive` or
492 :meth:`verify` is
493 called more than
494 once.
495
496 This checks whether deriving a new key from the supplied
497 ``key_material`` generates the same key as the ``expected_key``, and
498 raises an exception if they do not match.
499
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400500.. currentmodule:: cryptography.hazmat.primitives.kdf.x963kdf
501
502.. class:: X963KDF(algorithm, length, otherinfo, backend)
503
504 .. versionadded:: 1.1
505
506 X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI
507 in the `ANSI X9.63:2001`_ document, to be used to derive keys for use
508 after a Key Exchange negotiation operation.
509
510 SECG in `SEC 1 v2.0`_ recommends that
511 :class:`~cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash` be
512 used for new projects. This KDF should only be used for backwards
Alex Gaynorace036d2015-09-24 20:23:08 -0400513 compatibility with pre-existing protocols.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400514
515
516 .. warning::
517
518 X963KDF should not be used for password storage.
519
520 .. doctest::
521
522 >>> import os
523 >>> from cryptography.hazmat.primitives import hashes
524 >>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
525 >>> from cryptography.hazmat.backends import default_backend
526 >>> backend = default_backend()
527 >>> sharedinfo = b"ANSI X9.63 Example"
528 >>> xkdf = X963KDF(
529 ... algorithm=hashes.SHA256(),
530 ... length=256,
531 ... sharedinfo=sharedinfo,
532 ... backend=backend
533 ... )
534 >>> key = xkdf.derive(b"input key")
535 >>> xkdf = X963KDF(
536 ... algorithm=hashes.SHA256(),
537 ... length=256,
538 ... sharedinfo=sharedinfo,
539 ... backend=backend
540 ... )
541 >>> xkdf.verify(b"input key", key)
542
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300543 :param algorithm: An instance of
544 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400545
546 :param int length: The desired length of the derived key in bytes.
547 Maximum is ``hashlen * (2^32 -1)``.
548
549 :param bytes sharedinfo: Application specific context information.
550 If ``None`` is explicitly passed an empty byte string will be used.
551
552 :param backend: A cryptography backend
553 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300554 instance.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400555
556 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
557 if the provided ``backend`` does not implement
558 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
559
560 :raises TypeError: This exception is raised if ``sharedinfo`` is not
561 ``bytes``.
562
563 .. method:: derive(key_material)
564
565 :param bytes key_material: The input key material.
566 :return bytes: The derived key.
567 :raises TypeError: This exception is raised if ``key_material`` is
568 not ``bytes``.
569
570 Derives a new key from the input key material.
571
572 .. method:: verify(key_material, expected_key)
573
574 :param bytes key_material: The input key material. This is the same as
575 ``key_material`` in :meth:`derive`.
576 :param bytes expected_key: The expected result of deriving a new key,
577 this is the same as the return value of
578 :meth:`derive`.
579 :raises cryptography.exceptions.InvalidKey: This is raised when the
580 derived key does not match
581 the expected key.
582 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
583 :meth:`derive` or
584 :meth:`verify` is
585 called more than
586 once.
587
588 This checks whether deriving a new key from the supplied
589 ``key_material`` generates the same key as the ``expected_key``, and
590 raises an exception if they do not match.
591
Simo Sorce8a690fb2015-05-01 15:56:30 -0400592
Jared6d7fe002016-05-29 17:32:37 -0700593.. currentmodule:: cryptography.hazmat.primitives.kdf.kbkdf
594
595.. class:: KBKDFHMAC(algorithm, mode, length, rlen, llen, location,\
596 label, context, fixed, backend)
597
598 .. versionadded:: 1.4
599
600 KBKDF (Key Based Key Derivation Function) is defined by the
601 `NIST SP 800-108`_ document, to be used to derive additional
602 keys from a key that has been established through an automated
603 key-establishment scheme.
604
605 .. warning::
606
607 KBKDFHMAC should not be used for password storage.
608
609 .. doctest::
610
611 >>> import os
612 >>> from cryptography.hazmat.primitives import hashes
613 >>> from cryptography.hazmat.primitives.kdf.kbkdf import (
614 ... CounterLocation, KBKDFHMAC, Mode
615 ... )
616 >>> from cryptography.hazmat.backends import default_backend
617 >>> backend = default_backend()
618 >>> label = b"KBKDF HMAC Label"
619 >>> context = b"KBKDF HMAC Context"
620 >>> kdf = KBKDFHMAC(
621 ... algorithm=hashes.SHA256(),
622 ... mode=Mode.CounterMode,
623 ... length=256,
624 ... rlen=4,
625 ... llen=4,
626 ... location=CounterLocation.BeforeFixed,
627 ... label=label,
628 ... context=context,
629 ... fixed=None,
630 ... backend=backend
631 ... )
632 >>> key = kdf.derive(b"input key")
633 >>> kdf = KBKDFHMAC(
634 ... algorithm=hashes.SHA256(),
635 ... mode=Mode.CounterMode,
636 ... length=256,
637 ... rlen=4,
638 ... llen=4,
639 ... location=CounterLocation.BeforeFixed,
640 ... label=label,
641 ... context=context,
642 ... fixed=None,
643 ... backend=backend
644 ... )
645 >>> kdf.verify(b"input key", key)
646
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300647 :param algorithm: An instance of
648 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Jared6d7fe002016-05-29 17:32:37 -0700649
650 :param mode: The desired mode of the PRF. A value from the
651 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.Mode` enum.
652
653 :param int length: The desired length of the derived key in bytes.
654
655 :param int rlen: An integer that indicates the length of the binary
656 representation of the counter in bytes.
657
658 :param int llen: An integer that indicates the binary
659 representation of the ``length`` in bytes.
660
661 :param location: The desired location of the counter. A value from the
662 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation` enum.
663
664 :param bytes label: Application specific label information. If ``None``
665 is explicitly passed an empty byte string will be used.
666
667 :param bytes context: Application specific context information. If ``None``
668 is explicitly passed an empty byte string will be used.
669
670 :param bytes fixed: Instead of specifying ``label`` and ``context`` you
671 may supply your own fixed data. If ``fixed`` is specified, ``label``
672 and ``context`` is ignored.
673
674 :param backend: A cryptography backend
675 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300676 instance.
Jared6d7fe002016-05-29 17:32:37 -0700677
678 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
679 if the provided ``backend`` does not implement
680 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
681
682 :raises TypeError: This exception is raised if ``label`` or ``context``
683 is not ``bytes``. Also raised if ``rlen`` or ``llen`` is not ``int``.
684
685 :raises ValueError: This exception is raised if ``rlen`` or ``llen``
686 is greater than 4 or less than 1. This exception is also raised if
687 you specify a ``label`` or ``context`` and ``fixed``.
688
689 .. method:: derive(key_material)
690
691 :param bytes key_material: The input key material.
692 :return bytes: The derived key.
693 :raises TypeError: This exception is raised if ``key_material`` is
694 not ``bytes``.
695
696 Derives a new key from the input key material.
697
698 .. method:: verify(key_material, expected_key)
699
700 :param bytes key_material: The input key material. This is the same as
701 ``key_material`` in :meth:`derive`.
702 :param bytes expected_key: The expected result of deriving a new key,
703 this is the same as the return value of
704 :meth:`derive`.
705 :raises cryptography.exceptions.InvalidKey: This is raised when the
706 derived key does not match
707 the expected key.
708 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
709 :meth:`derive` or
710 :meth:`verify` is
711 called more than
712 once.
713
714 This checks whether deriving a new key from the supplied
715 ``key_material`` generates the same key as the ``expected_key``, and
716 raises an exception if they do not match.
717
718.. class:: Mode
719
720 An enumeration for the key based key derivative modes.
721
722 .. attribute:: CounterMode
723
724 The output of the PRF is computed with a counter
725 as the iteration variable.
726
727.. class:: CounterLocation
728
729 An enumeration for the key based key derivative counter location.
730
731 .. attribute:: BeforeFixed
732
733 The counter iteration variable will be concatenated before
734 the fixed input data.
735
736 .. attribute:: AfterFixed
737
738 The counter iteration variable will be concatenated after
739 the fixed input data.
740
Terry Chiad8a27df2016-09-01 23:39:57 +0800741.. currentmodule:: cryptography.hazmat.primitives.kdf.scrypt
742
743.. class:: Scrypt(salt, length, n, r, p, backend)
744
745 .. versionadded:: 1.6
746
747 Scrypt is a KDF designed for password storage by Colin Percival to be
748 resistant against hardware-assisted attackers by having a tunable memory
749 cost. It is described in :rfc:`7914`.
750
751 This class conforms to the
752 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
753 interface.
754
755 .. code-block:: python
756
757 >>> import os
758 >>> from cryptography.hazmat.primitives import hashes
759 >>> from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
760 >>> from cryptography.hazmat.backends import default_backend
761 >>> backend = default_backend()
762 >>> salt = os.urandom(16)
763 >>> # derive
764 >>> kdf = Scrypt(
765 ... salt=salt,
766 ... length=64,
767 ... n=1024,
768 ... r=8,
769 ... p=16,
770 ... backend=backend
771 ... )
772 >>> key = kdf.derive(b"my great password")
773 >>> # verify
774 >>> kdf = Scrypt(
775 ... salt=salt,
776 ... length=64,
777 ... n=1024,
778 ... r=8,
779 ... p=16,
780 ... backend=backend
781 ... )
782 >>> kdf.verify(b"my great password", key)
783
784 :param bytes salt: A salt.
785 :param int length: The desired length of the derived key.
786 :param int n: CPU/Memory cost parameter. It must be larger than 1 and be a
787 power of 2.
788 :param int r: Block size parameter.
789 :param int p: Parallelization parameter.
790
791 The computational and memory cost of Scrypt can be adjusted by manipulating
792 the 3 parameters: n, r and p. In general, the memory cost of Scrypt is
793 affected by the values of both n and r while n also determines the number
794 of iterations performed. p increases the computational cost without
795 affecting memory usage. A more in-depth explanation of the 3 parameters can
796 be found `here`_.
797
798 :rfc:`7914` `recommends`_ values of r=8 and p=1 while scaling n to the
799 number appropriate for your system.
800
801 :param backend: An instance of
802 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`.
803
804 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
805 provided ``backend`` does not implement
806 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`
807
808 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Terry Chiaa2d0da92016-09-03 07:57:45 +0800809 :raises ValueError: This exception is raised if ``n`` is less than 2, if
810 ``n`` is not a power of 2, if ``r`` is less than 1 or if ``p`` is less
811 than 1.
Terry Chiad8a27df2016-09-01 23:39:57 +0800812
813 .. method:: derive(key_material)
814
815 :param bytes key_material: The input key material.
816 :return bytes: the derived key.
817 :raises TypeError: This exception is raised if ``key_material`` is not
818 ``bytes``.
819 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
820 :meth:`derive` or
821 :meth:`verify` is
822 called more than
823 once.
824
825 This generates and returns a new key from the supplied password.
826
827 .. method:: verify(key_material, expected_key)
828
829 :param bytes key_material: The input key material. This is the same as
830 ``key_material`` in :meth:`derive`.
831 :param bytes expected_key: The expected result of deriving a new key,
832 this is the same as the return value of
833 :meth:`derive`.
834 :raises cryptography.exceptions.InvalidKey: This is raised when the
835 derived key does not match
836 the expected key.
837 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
838 :meth:`derive` or
839 :meth:`verify` is
840 called more than
841 once.
842
843 This checks whether deriving a new key from the supplied
844 ``key_material`` generates the same key as the ``expected_key``, and
845 raises an exception if they do not match. This can be used for
846 checking whether the password a user provides matches the stored derived
847 key.
848
Paul Kehrer48402ff2015-02-16 15:31:52 -0600849Interface
850~~~~~~~~~
851
852.. currentmodule:: cryptography.hazmat.primitives.kdf
853
854.. class:: KeyDerivationFunction
855
856 .. versionadded:: 0.2
857
858 .. method:: derive(key_material)
859
860 :param bytes key_material: The input key material. Depending on what
861 key derivation function you are using this
862 could be either random bytes, or a user
863 supplied password.
864 :return: The new key.
865 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
866 :meth:`derive` or
867 :meth:`verify` is
868 called more than
869 once.
870
871 This generates and returns a new key from the supplied key material.
872
873 .. method:: verify(key_material, expected_key)
874
875 :param bytes key_material: The input key material. This is the same as
876 ``key_material`` in :meth:`derive`.
877 :param bytes expected_key: The expected result of deriving a new key,
878 this is the same as the return value of
879 :meth:`derive`.
880 :raises cryptography.exceptions.InvalidKey: This is raised when the
881 derived key does not match
882 the expected key.
883 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
884 :meth:`derive` or
885 :meth:`verify` is
886 called more than
887 once.
888
889 This checks whether deriving a new key from the supplied
890 ``key_material`` generates the same key as the ``expected_key``, and
891 raises an exception if they do not match. This can be used for
892 something like checking whether a user's password attempt matches the
893 stored derived key.
894
895
Paul Kehrerb6d764c2014-01-27 22:32:11 -0600896.. _`NIST SP 800-132`: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
Jared6d7fe002016-05-29 17:32:37 -0700897.. _`NIST SP 800-108`: http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf
Simo Sorce8a690fb2015-05-01 15:56:30 -0400898.. _`NIST SP 800-56Ar2`: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400899.. _`ANSI X9.63:2001`: https://webstore.ansi.org
900.. _`SEC 1 v2.0`: http://www.secg.org/sec1-v2.pdf
Paul Kehrerb3f763f2014-01-28 16:42:15 -0600901.. _`Password Storage Cheat Sheet`: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
David Reidb80deea2014-02-03 10:33:16 -0800902.. _`PBKDF2`: https://en.wikipedia.org/wiki/PBKDF2
David Reidb80deea2014-02-03 10:33:16 -0800903.. _`key stretching`: https://en.wikipedia.org/wiki/Key_stretching
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400904.. _`HKDF`: https://en.wikipedia.org/wiki/HKDF
David Reidb80deea2014-02-03 10:33:16 -0800905.. _`HKDF paper`: https://eprint.iacr.org/2010/264
Terry Chiad8a27df2016-09-01 23:39:57 +0800906.. _`here`: https://stackoverflow.com/a/30308723/1170681
907.. _`recommends`: https://tools.ietf.org/html/rfc7914#section-2