blob: 03260c06b67553e5215f1c50def3d95f92e8b010 [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
Paul Kehrer0b181182014-01-29 16:34:47 -060037 key storage, but an alternate key storage KDF such as `scrypt`_ is generally
Paul Kehrer1cab1042014-01-29 14:30:11 -060038 considered a better solution.
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060039
Paul Kehrer5d1af212014-01-28 12:19:32 -060040 This class conforms to the
Paul Kehrer48402ff2015-02-16 15:31:52 -060041 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
Paul Kehrer5d1af212014-01-28 12:19:32 -060042 interface.
43
Paul Kehrerb6d764c2014-01-27 22:32:11 -060044 .. doctest::
45
Paul Kehrer5d1af212014-01-28 12:19:32 -060046 >>> import os
47 >>> from cryptography.hazmat.primitives import hashes
Paul Kehrerb3f763f2014-01-28 16:42:15 -060048 >>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
Paul Kehrerb6d764c2014-01-27 22:32:11 -060049 >>> from cryptography.hazmat.backends import default_backend
50 >>> backend = default_backend()
51 >>> salt = os.urandom(16)
52 >>> # derive
Paul Kehrerb3f763f2014-01-28 16:42:15 -060053 >>> kdf = PBKDF2HMAC(
54 ... algorithm=hashes.SHA256(),
55 ... length=32,
56 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060057 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060058 ... backend=backend
59 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060060 >>> key = kdf.derive(b"my great password")
61 >>> # verify
Paul Kehrerb3f763f2014-01-28 16:42:15 -060062 >>> kdf = PBKDF2HMAC(
63 ... algorithm=hashes.SHA256(),
64 ... length=32,
65 ... salt=salt,
Paul Kehrer1277bc72014-01-28 17:09:59 -060066 ... iterations=100000,
Paul Kehrerb3f763f2014-01-28 16:42:15 -060067 ... backend=backend
68 ... )
Paul Kehrerb6d764c2014-01-27 22:32:11 -060069 >>> kdf.verify(b"my great password", key)
Paul Kehrerb6d764c2014-01-27 22:32:11 -060070
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030071 :param algorithm: An instance of
72 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Paul Kehrer5d1af212014-01-28 12:19:32 -060073 :param int length: The desired length of the derived key. Maximum is
Paul Kehrerb3f763f2014-01-28 16:42:15 -060074 (2\ :sup:`32` - 1) * ``algorithm.digest_size``.
Paul Kehrer5d1af212014-01-28 12:19:32 -060075 :param bytes salt: A salt. `NIST SP 800-132`_ recommends 128-bits or
76 longer.
77 :param int iterations: The number of iterations to perform of the hash
Paul Kehrerc58b4782014-01-29 13:56:25 -060078 function. This can be used to control the length of time the operation
79 takes. Higher numbers help mitigate brute force attacks against derived
80 keys. See OWASP's `Password Storage Cheat Sheet`_ for more
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060081 detailed recommendations if you intend to use this for password storage.
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030082 :param backend: An instance of
83 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`.
Paul Kehrerb6d764c2014-01-27 22:32:11 -060084
Alex Gaynor7a489db2014-03-22 15:09:34 -070085 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +080086 provided ``backend`` does not implement
87 :class:`~cryptography.hazmat.backends.interfaces.PBKDF2HMACBackend`
88
Ayrx00eff9c2014-05-17 19:47:09 +080089 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +080090
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060091 .. method:: derive(key_material)
92
Alex Gaynora8e125f2014-01-29 19:21:03 -080093 :param bytes key_material: The input key material. For PBKDF2 this
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060094 should be a password.
Paul Kehrer0b181182014-01-29 16:34:47 -060095 :return bytes: the derived key.
Paul Kehrer3d8c66f2014-01-28 17:36:50 -060096 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
97 :meth:`derive` or
98 :meth:`verify` is
99 called more than
100 once.
101
Ayrx6d69eab2014-05-17 16:59:31 +0800102 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800103 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800104
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600105 This generates and returns a new key from the supplied password.
106
107 .. method:: verify(key_material, expected_key)
108
Alex Gaynora8e125f2014-01-29 19:21:03 -0800109 :param bytes key_material: The input key material. This is the same as
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600110 ``key_material`` in :meth:`derive`.
Alex Gaynora8e125f2014-01-29 19:21:03 -0800111 :param bytes expected_key: The expected result of deriving a new key,
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600112 this is the same as the return value of
113 :meth:`derive`.
114 :raises cryptography.exceptions.InvalidKey: This is raised when the
115 derived key does not match
116 the expected key.
117 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
118 :meth:`derive` or
119 :meth:`verify` is
120 called more than
121 once.
122
123 This checks whether deriving a new key from the supplied
124 ``key_material`` generates the same key as the ``expected_key``, and
125 raises an exception if they do not match. This can be used for
Paul Kehrer99d51902014-01-28 20:16:20 -0600126 checking whether the password a user provides matches the stored derived
Paul Kehrer3d8c66f2014-01-28 17:36:50 -0600127 key.
128
David Reidc0248b92014-01-30 15:23:33 -0800129
130.. currentmodule:: cryptography.hazmat.primitives.kdf.hkdf
131
132.. class:: HKDF(algorithm, length, salt, info, backend)
133
134 .. versionadded:: 0.2
135
David Reid2ad94ab2014-02-03 10:01:15 -0800136 `HKDF`_ (HMAC-based Extract-and-Expand Key Derivation Function) is suitable
David Reidc0248b92014-01-30 15:23:33 -0800137 for deriving keys of a fixed size used for other cryptographic operations.
Alex Gaynorc43bb752014-02-12 16:42:11 -0800138
139 .. warning::
140
141 HKDF should not be used for password storage.
David Reidc0248b92014-01-30 15:23:33 -0800142
David Reid5df929c2014-02-03 13:26:15 -0800143 .. doctest::
144
145 >>> import os
146 >>> from cryptography.hazmat.primitives import hashes
147 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
148 >>> from cryptography.hazmat.backends import default_backend
149 >>> backend = default_backend()
150 >>> salt = os.urandom(16)
151 >>> info = b"hkdf-example"
152 >>> hkdf = HKDF(
153 ... algorithm=hashes.SHA256(),
154 ... length=32,
155 ... salt=salt,
156 ... info=info,
157 ... backend=backend
158 ... )
David Reid134f1f42014-02-03 13:54:30 -0800159 >>> key = hkdf.derive(b"input key")
David Reid5df929c2014-02-03 13:26:15 -0800160 >>> hkdf = HKDF(
161 ... algorithm=hashes.SHA256(),
162 ... length=32,
163 ... salt=salt,
164 ... info=info,
165 ... backend=backend
166 ... )
167 >>> hkdf.verify(b"input key", key)
168
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300169 :param algorithm: An instance of
170 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
David Reidc0248b92014-01-30 15:23:33 -0800171
172 :param int length: The desired length of the derived key. Maximum is
David Reidb89f34c2014-02-03 10:01:42 -0800173 ``255 * (algorithm.digest_size // 8)``.
David Reidc0248b92014-01-30 15:23:33 -0800174
David Reid2ad94ab2014-02-03 10:01:15 -0800175 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
176 highly recommended. Ideally as many bits of entropy as the security
177 level of the hash: often that means cryptographically random and as
178 long as the hash output. Worse (shorter, less entropy) salt values can
179 still meaningfully contribute to security. May be reused. Does not have
180 to be secret, but may cause stronger security guarantees if secret; see
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400181 :rfc:`5869` and the `HKDF paper`_ for more details. If ``None`` is
David Reid2ad94ab2014-02-03 10:01:15 -0800182 explicitly passed a default salt of ``algorithm.digest_size // 8`` null
183 bytes will be used.
David Reidc0248b92014-01-30 15:23:33 -0800184
185 :param bytes info: Application specific context information. If ``None``
186 is explicitly passed an empty byte string will be used.
187
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300188 :param backend: An instance of
189 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
David Reidc0248b92014-01-30 15:23:33 -0800190
Alex Gaynor7a489db2014-03-22 15:09:34 -0700191 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrx68702412014-03-15 23:29:36 +0800192 provided ``backend`` does not implement
193 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
194
Ayrx6d69eab2014-05-17 16:59:31 +0800195 :raises TypeError: This exception is raised if ``salt`` or ``info`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800196 ``bytes``.
Ayrx6d69eab2014-05-17 16:59:31 +0800197
David Reidc0248b92014-01-30 15:23:33 -0800198 .. method:: derive(key_material)
199
200 :param bytes key_material: The input key material.
Ayrx1534e092014-05-06 14:19:46 +0800201 :return bytes: The derived key.
Ayrx6d69eab2014-05-17 16:59:31 +0800202 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800203 ``bytes``.
David Reidc0248b92014-01-30 15:23:33 -0800204
205 Derives a new key from the input key material by performing both the
206 extract and expand operations.
207
208 .. method:: verify(key_material, expected_key)
209
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600210 :param bytes key_material: The input key material. This is the same as
David Reidc0248b92014-01-30 15:23:33 -0800211 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600212 :param bytes expected_key: The expected result of deriving a new key,
David Reidc0248b92014-01-30 15:23:33 -0800213 this is the same as the return value of
214 :meth:`derive`.
215 :raises cryptography.exceptions.InvalidKey: This is raised when the
216 derived key does not match
217 the expected key.
218 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
219 :meth:`derive` or
220 :meth:`verify` is
221 called more than
222 once.
223
224 This checks whether deriving a new key from the supplied
225 ``key_material`` generates the same key as the ``expected_key``, and
David Reidb9fa7712014-02-03 10:45:11 -0800226 raises an exception if they do not match.
David Reidc0248b92014-01-30 15:23:33 -0800227
Ayrx9d72f122014-05-06 20:27:51 +0800228
Ayrxc0ce9112014-05-07 16:22:09 +0800229.. class:: HKDFExpand(algorithm, length, info, backend)
Ayrx9d72f122014-05-06 20:27:51 +0800230
231 .. versionadded:: 0.5
232
233 HKDF consists of two stages, extract and expand. This class exposes an
234 expand only version of HKDF that is suitable when the key material is
235 already cryptographically strong.
236
237 .. warning::
238
Ayrxc0ce9112014-05-07 16:22:09 +0800239 HKDFExpand should only be used if the key material is
Ayrx9d72f122014-05-06 20:27:51 +0800240 cryptographically strong. You should use
241 :class:`~cryptography.hazmat.primitives.kdf.hkdf.HKDF` if
242 you are unsure.
243
244 .. doctest::
245
246 >>> import os
247 >>> from cryptography.hazmat.primitives import hashes
Ayrxc0ce9112014-05-07 16:22:09 +0800248 >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
Ayrx9d72f122014-05-06 20:27:51 +0800249 >>> from cryptography.hazmat.backends import default_backend
250 >>> backend = default_backend()
251 >>> info = b"hkdf-example"
252 >>> key_material = os.urandom(16)
Ayrxc0ce9112014-05-07 16:22:09 +0800253 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800254 ... algorithm=hashes.SHA256(),
255 ... length=32,
256 ... info=info,
257 ... backend=backend
258 ... )
259 >>> key = hkdf.derive(key_material)
Ayrxc0ce9112014-05-07 16:22:09 +0800260 >>> hkdf = HKDFExpand(
Ayrx9d72f122014-05-06 20:27:51 +0800261 ... algorithm=hashes.SHA256(),
262 ... length=32,
263 ... info=info,
264 ... backend=backend
265 ... )
266 >>> hkdf.verify(key_material, key)
267
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300268 :param algorithm: An instance of
269 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Ayrx9d72f122014-05-06 20:27:51 +0800270
271 :param int length: The desired length of the derived key. Maximum is
272 ``255 * (algorithm.digest_size // 8)``.
273
274 :param bytes info: Application specific context information. If ``None``
275 is explicitly passed an empty byte string will be used.
276
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300277 :param backend: An instance of
278 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Ayrx9d72f122014-05-06 20:27:51 +0800279
280 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
281 provided ``backend`` does not implement
282 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
Ayrxc48100a2014-05-10 13:01:46 +0800283 :raises TypeError: This is raised if the provided ``info`` is a unicode object
Ayrx00eff9c2014-05-17 19:47:09 +0800284 :raises TypeError: This exception is raised if ``info`` is not ``bytes``.
Ayrx9d72f122014-05-06 20:27:51 +0800285
286 .. method:: derive(key_material)
287
288 :param bytes key_material: The input key material.
289 :return bytes: The derived key.
290
Ayrxc48100a2014-05-10 13:01:46 +0800291 :raises TypeError: This is raised if the provided ``key_material`` is
292 a unicode object
Ayrx6d69eab2014-05-17 16:59:31 +0800293 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800294 ``bytes``.
Ayrxc48100a2014-05-10 13:01:46 +0800295
Ayrx9d72f122014-05-06 20:27:51 +0800296 Derives a new key from the input key material by performing both the
297 extract and expand operations.
298
299 .. method:: verify(key_material, expected_key)
300
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600301 :param bytes key_material: The input key material. This is the same as
Ayrx9d72f122014-05-06 20:27:51 +0800302 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600303 :param bytes expected_key: The expected result of deriving a new key,
Ayrx9d72f122014-05-06 20:27:51 +0800304 this is the same as the return value of
305 :meth:`derive`.
306 :raises cryptography.exceptions.InvalidKey: This is raised when the
307 derived key does not match
308 the expected key.
309 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
310 :meth:`derive` or
311 :meth:`verify` is
312 called more than
313 once.
Ayrxc48100a2014-05-10 13:01:46 +0800314 :raises TypeError: This is raised if the provided ``key_material`` is
315 a unicode object
Ayrx9d72f122014-05-06 20:27:51 +0800316
317 This checks whether deriving a new key from the supplied
318 ``key_material`` generates the same key as the ``expected_key``, and
319 raises an exception if they do not match.
320
Simo Sorce8a690fb2015-05-01 15:56:30 -0400321.. currentmodule:: cryptography.hazmat.primitives.kdf.concatkdf
322
323.. class:: ConcatKDFHash(algorithm, length, otherinfo, backend)
324
325 .. versionadded:: 1.0
326
327 ConcatKDFHash (Concatenation Key Derivation Function) is defined by the
328 NIST Special Publication `NIST SP 800-56Ar2`_ document, to be used to
329 derive keys for use after a Key Exchange negotiation operation.
330
331 .. warning::
332
333 ConcatKDFHash should not be used for password storage.
334
335 .. doctest::
336
337 >>> import os
338 >>> from cryptography.hazmat.primitives import hashes
339 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
340 >>> from cryptography.hazmat.backends import default_backend
341 >>> backend = default_backend()
Simo Sorce8a690fb2015-05-01 15:56:30 -0400342 >>> otherinfo = b"concatkdf-example"
343 >>> ckdf = ConcatKDFHash(
344 ... algorithm=hashes.SHA256(),
345 ... length=256,
346 ... otherinfo=otherinfo,
347 ... backend=backend
348 ... )
349 >>> key = ckdf.derive(b"input key")
350 >>> ckdf = ConcatKDFHash(
351 ... algorithm=hashes.SHA256(),
352 ... length=256,
353 ... otherinfo=otherinfo,
354 ... backend=backend
355 ... )
356 >>> ckdf.verify(b"input key", key)
357
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300358 :param algorithm: An instance of
359 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400360
361 :param int length: The desired length of the derived key in bytes.
362 Maximum is ``hashlen * (2^32 -1)``.
363
364 :param bytes otherinfo: Application specific context information.
365 If ``None`` is explicitly passed an empty byte string will be used.
366
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300367 :param backend: An instance of
368 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400369
370 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
371 if the provided ``backend`` does not implement
372 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
373
374 :raises TypeError: This exception is raised if ``otherinfo`` is not
375 ``bytes``.
376
377 .. method:: derive(key_material)
378
379 :param bytes key_material: The input key material.
380 :return bytes: The derived key.
381 :raises TypeError: This exception is raised if ``key_material`` is
382 not ``bytes``.
383
Terry Chiadae40762015-06-13 11:26:16 +0800384 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400385
386 .. method:: verify(key_material, expected_key)
387
388 :param bytes key_material: The input key material. This is the same as
389 ``key_material`` in :meth:`derive`.
390 :param bytes expected_key: The expected result of deriving a new key,
391 this is the same as the return value of
392 :meth:`derive`.
393 :raises cryptography.exceptions.InvalidKey: This is raised when the
394 derived key does not match
395 the expected key.
396 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
397 :meth:`derive` or
398 :meth:`verify` is
399 called more than
400 once.
401
402 This checks whether deriving a new key from the supplied
403 ``key_material`` generates the same key as the ``expected_key``, and
404 raises an exception if they do not match.
405
406
407.. class:: ConcatKDFHMAC(algorithm, length, salt, otherinfo, backend)
408
409 .. versionadded:: 1.0
410
411 Similar to ConcatKFDHash but uses an HMAC function instead.
412
413 .. warning::
414
415 ConcatKDFHMAC should not be used for password storage.
416
417 .. doctest::
418
419 >>> import os
420 >>> from cryptography.hazmat.primitives import hashes
421 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC
422 >>> from cryptography.hazmat.backends import default_backend
423 >>> backend = default_backend()
424 >>> salt = os.urandom(16)
425 >>> otherinfo = b"concatkdf-example"
426 >>> ckdf = ConcatKDFHMAC(
427 ... algorithm=hashes.SHA256(),
428 ... length=256,
429 ... salt=salt,
430 ... otherinfo=otherinfo,
431 ... backend=backend
432 ... )
433 >>> key = ckdf.derive(b"input key")
434 >>> ckdf = ConcatKDFHMAC(
435 ... algorithm=hashes.SHA256(),
436 ... length=256,
437 ... salt=salt,
438 ... otherinfo=otherinfo,
439 ... backend=backend
440 ... )
441 >>> ckdf.verify(b"input key", key)
442
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300443 :param algorithm: An instance of
444 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400445
446 :param int length: The desired length of the derived key in bytes. Maximum
447 is ``hashlen * (2^32 -1)``.
448
449 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
450 highly recommended. Ideally as many bits of entropy as the security
451 level of the hash: often that means cryptographically random and as
452 long as the hash output. Does not have to be secret, but may cause
453 stronger security guarantees if secret; If ``None`` is explicitly
454 passed a default salt of ``algorithm.block_size`` null bytes will be
455 used.
456
457 :param bytes otherinfo: Application specific context information.
458 If ``None`` is explicitly passed an empty byte string will be used.
459
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300460 :param backend: An instance of
461 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400462
463 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
464 provided ``backend`` does not implement
465 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
466
467 :raises TypeError: This exception is raised if ``salt`` or ``otherinfo``
468 is not ``bytes``.
469
470 .. method:: derive(key_material)
471
472 :param bytes key_material: The input key material.
473 :return bytes: The derived key.
474 :raises TypeError: This exception is raised if ``key_material`` is not
475 ``bytes``.
476
Terry Chiadae40762015-06-13 11:26:16 +0800477 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400478
479 .. method:: verify(key_material, expected_key)
480
481 :param bytes key_material: The input key material. This is the same as
482 ``key_material`` in :meth:`derive`.
483 :param bytes expected_key: The expected result of deriving a new key,
484 this is the same as the return value of
485 :meth:`derive`.
486 :raises cryptography.exceptions.InvalidKey: This is raised when the
487 derived key does not match
488 the expected key.
489 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
490 :meth:`derive` or
491 :meth:`verify` is
492 called more than
493 once.
494
495 This checks whether deriving a new key from the supplied
496 ``key_material`` generates the same key as the ``expected_key``, and
497 raises an exception if they do not match.
498
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400499.. currentmodule:: cryptography.hazmat.primitives.kdf.x963kdf
500
501.. class:: X963KDF(algorithm, length, otherinfo, backend)
502
503 .. versionadded:: 1.1
504
505 X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI
506 in the `ANSI X9.63:2001`_ document, to be used to derive keys for use
507 after a Key Exchange negotiation operation.
508
509 SECG in `SEC 1 v2.0`_ recommends that
510 :class:`~cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash` be
511 used for new projects. This KDF should only be used for backwards
Alex Gaynorace036d2015-09-24 20:23:08 -0400512 compatibility with pre-existing protocols.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400513
514
515 .. warning::
516
517 X963KDF should not be used for password storage.
518
519 .. doctest::
520
521 >>> import os
522 >>> from cryptography.hazmat.primitives import hashes
523 >>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
524 >>> from cryptography.hazmat.backends import default_backend
525 >>> backend = default_backend()
526 >>> sharedinfo = b"ANSI X9.63 Example"
527 >>> xkdf = X963KDF(
528 ... algorithm=hashes.SHA256(),
529 ... length=256,
530 ... sharedinfo=sharedinfo,
531 ... backend=backend
532 ... )
533 >>> key = xkdf.derive(b"input key")
534 >>> xkdf = X963KDF(
535 ... algorithm=hashes.SHA256(),
536 ... length=256,
537 ... sharedinfo=sharedinfo,
538 ... backend=backend
539 ... )
540 >>> xkdf.verify(b"input key", key)
541
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300542 :param algorithm: An instance of
543 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400544
545 :param int length: The desired length of the derived key in bytes.
546 Maximum is ``hashlen * (2^32 -1)``.
547
548 :param bytes sharedinfo: Application specific context information.
549 If ``None`` is explicitly passed an empty byte string will be used.
550
551 :param backend: A cryptography backend
552 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300553 instance.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400554
555 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
556 if the provided ``backend`` does not implement
557 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
558
559 :raises TypeError: This exception is raised if ``sharedinfo`` is not
560 ``bytes``.
561
562 .. method:: derive(key_material)
563
564 :param bytes key_material: The input key material.
565 :return bytes: The derived key.
566 :raises TypeError: This exception is raised if ``key_material`` is
567 not ``bytes``.
568
569 Derives a new key from the input key material.
570
571 .. method:: verify(key_material, expected_key)
572
573 :param bytes key_material: The input key material. This is the same as
574 ``key_material`` in :meth:`derive`.
575 :param bytes expected_key: The expected result of deriving a new key,
576 this is the same as the return value of
577 :meth:`derive`.
578 :raises cryptography.exceptions.InvalidKey: This is raised when the
579 derived key does not match
580 the expected key.
581 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
582 :meth:`derive` or
583 :meth:`verify` is
584 called more than
585 once.
586
587 This checks whether deriving a new key from the supplied
588 ``key_material`` generates the same key as the ``expected_key``, and
589 raises an exception if they do not match.
590
Simo Sorce8a690fb2015-05-01 15:56:30 -0400591
Jared6d7fe002016-05-29 17:32:37 -0700592.. currentmodule:: cryptography.hazmat.primitives.kdf.kbkdf
593
594.. class:: KBKDFHMAC(algorithm, mode, length, rlen, llen, location,\
595 label, context, fixed, backend)
596
597 .. versionadded:: 1.4
598
599 KBKDF (Key Based Key Derivation Function) is defined by the
600 `NIST SP 800-108`_ document, to be used to derive additional
601 keys from a key that has been established through an automated
602 key-establishment scheme.
603
604 .. warning::
605
606 KBKDFHMAC should not be used for password storage.
607
608 .. doctest::
609
610 >>> import os
611 >>> from cryptography.hazmat.primitives import hashes
612 >>> from cryptography.hazmat.primitives.kdf.kbkdf import (
613 ... CounterLocation, KBKDFHMAC, Mode
614 ... )
615 >>> from cryptography.hazmat.backends import default_backend
616 >>> backend = default_backend()
617 >>> label = b"KBKDF HMAC Label"
618 >>> context = b"KBKDF HMAC Context"
619 >>> kdf = KBKDFHMAC(
620 ... algorithm=hashes.SHA256(),
621 ... mode=Mode.CounterMode,
622 ... length=256,
623 ... rlen=4,
624 ... llen=4,
625 ... location=CounterLocation.BeforeFixed,
626 ... label=label,
627 ... context=context,
628 ... fixed=None,
629 ... backend=backend
630 ... )
631 >>> key = kdf.derive(b"input key")
632 >>> kdf = KBKDFHMAC(
633 ... algorithm=hashes.SHA256(),
634 ... mode=Mode.CounterMode,
635 ... length=256,
636 ... rlen=4,
637 ... llen=4,
638 ... location=CounterLocation.BeforeFixed,
639 ... label=label,
640 ... context=context,
641 ... fixed=None,
642 ... backend=backend
643 ... )
644 >>> kdf.verify(b"input key", key)
645
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300646 :param algorithm: An instance of
647 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Jared6d7fe002016-05-29 17:32:37 -0700648
649 :param mode: The desired mode of the PRF. A value from the
650 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.Mode` enum.
651
652 :param int length: The desired length of the derived key in bytes.
653
654 :param int rlen: An integer that indicates the length of the binary
655 representation of the counter in bytes.
656
657 :param int llen: An integer that indicates the binary
658 representation of the ``length`` in bytes.
659
660 :param location: The desired location of the counter. A value from the
661 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation` enum.
662
663 :param bytes label: Application specific label information. If ``None``
664 is explicitly passed an empty byte string will be used.
665
666 :param bytes context: Application specific context information. If ``None``
667 is explicitly passed an empty byte string will be used.
668
669 :param bytes fixed: Instead of specifying ``label`` and ``context`` you
670 may supply your own fixed data. If ``fixed`` is specified, ``label``
671 and ``context`` is ignored.
672
673 :param backend: A cryptography backend
674 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300675 instance.
Jared6d7fe002016-05-29 17:32:37 -0700676
677 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
678 if the provided ``backend`` does not implement
679 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
680
681 :raises TypeError: This exception is raised if ``label`` or ``context``
682 is not ``bytes``. Also raised if ``rlen`` or ``llen`` is not ``int``.
683
684 :raises ValueError: This exception is raised if ``rlen`` or ``llen``
685 is greater than 4 or less than 1. This exception is also raised if
686 you specify a ``label`` or ``context`` and ``fixed``.
687
688 .. method:: derive(key_material)
689
690 :param bytes key_material: The input key material.
691 :return bytes: The derived key.
692 :raises TypeError: This exception is raised if ``key_material`` is
693 not ``bytes``.
694
695 Derives a new key from the input key material.
696
697 .. method:: verify(key_material, expected_key)
698
699 :param bytes key_material: The input key material. This is the same as
700 ``key_material`` in :meth:`derive`.
701 :param bytes expected_key: The expected result of deriving a new key,
702 this is the same as the return value of
703 :meth:`derive`.
704 :raises cryptography.exceptions.InvalidKey: This is raised when the
705 derived key does not match
706 the expected key.
707 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
708 :meth:`derive` or
709 :meth:`verify` is
710 called more than
711 once.
712
713 This checks whether deriving a new key from the supplied
714 ``key_material`` generates the same key as the ``expected_key``, and
715 raises an exception if they do not match.
716
717.. class:: Mode
718
719 An enumeration for the key based key derivative modes.
720
721 .. attribute:: CounterMode
722
723 The output of the PRF is computed with a counter
724 as the iteration variable.
725
726.. class:: CounterLocation
727
728 An enumeration for the key based key derivative counter location.
729
730 .. attribute:: BeforeFixed
731
732 The counter iteration variable will be concatenated before
733 the fixed input data.
734
735 .. attribute:: AfterFixed
736
737 The counter iteration variable will be concatenated after
738 the fixed input data.
739
Terry Chiad8a27df2016-09-01 23:39:57 +0800740.. currentmodule:: cryptography.hazmat.primitives.kdf.scrypt
741
742.. class:: Scrypt(salt, length, n, r, p, backend)
743
744 .. versionadded:: 1.6
745
746 Scrypt is a KDF designed for password storage by Colin Percival to be
747 resistant against hardware-assisted attackers by having a tunable memory
748 cost. It is described in :rfc:`7914`.
749
750 This class conforms to the
751 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
752 interface.
753
754 .. code-block:: python
755
756 >>> import os
757 >>> from cryptography.hazmat.primitives import hashes
758 >>> from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
759 >>> from cryptography.hazmat.backends import default_backend
760 >>> backend = default_backend()
761 >>> salt = os.urandom(16)
762 >>> # derive
763 >>> kdf = Scrypt(
764 ... salt=salt,
765 ... length=64,
766 ... n=1024,
767 ... r=8,
768 ... p=16,
769 ... backend=backend
770 ... )
771 >>> key = kdf.derive(b"my great password")
772 >>> # verify
773 >>> kdf = Scrypt(
774 ... salt=salt,
775 ... length=64,
776 ... n=1024,
777 ... r=8,
778 ... p=16,
779 ... backend=backend
780 ... )
781 >>> kdf.verify(b"my great password", key)
782
783 :param bytes salt: A salt.
784 :param int length: The desired length of the derived key.
785 :param int n: CPU/Memory cost parameter. It must be larger than 1 and be a
786 power of 2.
787 :param int r: Block size parameter.
788 :param int p: Parallelization parameter.
789
790 The computational and memory cost of Scrypt can be adjusted by manipulating
791 the 3 parameters: n, r and p. In general, the memory cost of Scrypt is
792 affected by the values of both n and r while n also determines the number
793 of iterations performed. p increases the computational cost without
794 affecting memory usage. A more in-depth explanation of the 3 parameters can
795 be found `here`_.
796
797 :rfc:`7914` `recommends`_ values of r=8 and p=1 while scaling n to the
798 number appropriate for your system.
799
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``.
808
809 .. method:: derive(key_material)
810
811 :param bytes key_material: The input key material.
812 :return bytes: the derived key.
813 :raises TypeError: This exception is raised if ``key_material`` is not
814 ``bytes``.
815 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
816 :meth:`derive` or
817 :meth:`verify` is
818 called more than
819 once.
820
821 This generates and returns a new key from the supplied password.
822
823 .. method:: verify(key_material, expected_key)
824
825 :param bytes key_material: The input key material. This is the same as
826 ``key_material`` in :meth:`derive`.
827 :param bytes expected_key: The expected result of deriving a new key,
828 this is the same as the return value of
829 :meth:`derive`.
830 :raises cryptography.exceptions.InvalidKey: This is raised when the
831 derived key does not match
832 the expected key.
833 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
834 :meth:`derive` or
835 :meth:`verify` is
836 called more than
837 once.
838
839 This checks whether deriving a new key from the supplied
840 ``key_material`` generates the same key as the ``expected_key``, and
841 raises an exception if they do not match. This can be used for
842 checking whether the password a user provides matches the stored derived
843 key.
844
Paul Kehrer48402ff2015-02-16 15:31:52 -0600845Interface
846~~~~~~~~~
847
848.. currentmodule:: cryptography.hazmat.primitives.kdf
849
850.. class:: KeyDerivationFunction
851
852 .. versionadded:: 0.2
853
854 .. method:: derive(key_material)
855
856 :param bytes key_material: The input key material. Depending on what
857 key derivation function you are using this
858 could be either random bytes, or a user
859 supplied password.
860 :return: The new key.
861 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
862 :meth:`derive` or
863 :meth:`verify` is
864 called more than
865 once.
866
867 This generates and returns a new key from the supplied key material.
868
869 .. method:: verify(key_material, expected_key)
870
871 :param bytes key_material: The input key material. This is the same as
872 ``key_material`` in :meth:`derive`.
873 :param bytes expected_key: The expected result of deriving a new key,
874 this is the same as the return value of
875 :meth:`derive`.
876 :raises cryptography.exceptions.InvalidKey: This is raised when the
877 derived key does not match
878 the expected key.
879 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
880 :meth:`derive` or
881 :meth:`verify` is
882 called more than
883 once.
884
885 This checks whether deriving a new key from the supplied
886 ``key_material`` generates the same key as the ``expected_key``, and
887 raises an exception if they do not match. This can be used for
888 something like checking whether a user's password attempt matches the
889 stored derived key.
890
891
Paul Kehrerb6d764c2014-01-27 22:32:11 -0600892.. _`NIST SP 800-132`: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
Jared6d7fe002016-05-29 17:32:37 -0700893.. _`NIST SP 800-108`: http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf
Simo Sorce8a690fb2015-05-01 15:56:30 -0400894.. _`NIST SP 800-56Ar2`: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400895.. _`ANSI X9.63:2001`: https://webstore.ansi.org
896.. _`SEC 1 v2.0`: http://www.secg.org/sec1-v2.pdf
Paul Kehrerb3f763f2014-01-28 16:42:15 -0600897.. _`Password Storage Cheat Sheet`: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
David Reidb80deea2014-02-03 10:33:16 -0800898.. _`PBKDF2`: https://en.wikipedia.org/wiki/PBKDF2
899.. _`scrypt`: https://en.wikipedia.org/wiki/Scrypt
900.. _`key stretching`: https://en.wikipedia.org/wiki/Key_stretching
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400901.. _`HKDF`: https://en.wikipedia.org/wiki/HKDF
David Reidb80deea2014-02-03 10:33:16 -0800902.. _`HKDF paper`: https://eprint.iacr.org/2010/264
Terry Chiad8a27df2016-09-01 23:39:57 +0800903.. _`here`: https://stackoverflow.com/a/30308723/1170681
904.. _`recommends`: https://tools.ietf.org/html/rfc7914#section-2