blob: d419b852e39a173b4d36da3488b2fdfce5289646 [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 Kehrer5d1af212014-01-28 12:19:32 -060075 :param int length: The desired length of the derived key. Maximum is
Paul Kehrerb3f763f2014-01-28 16:42:15 -060076 (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
174 :param int length: The desired length of the derived key. Maximum is
David Reidb89f34c2014-02-03 10:01:42 -0800175 ``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
273 :param int length: The desired length of the derived key. Maximum is
274 ``255 * (algorithm.digest_size // 8)``.
275
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`
Ayrxc48100a2014-05-10 13:01:46 +0800285 :raises TypeError: This is raised if the provided ``info`` is a unicode object
Ayrx00eff9c2014-05-17 19:47:09 +0800286 :raises TypeError: This exception is raised if ``info`` is not ``bytes``.
Ayrx9d72f122014-05-06 20:27:51 +0800287
288 .. method:: derive(key_material)
289
290 :param bytes key_material: The input key material.
291 :return bytes: The derived key.
292
Ayrxc48100a2014-05-10 13:01:46 +0800293 :raises TypeError: This is raised if the provided ``key_material`` is
294 a unicode object
Ayrx6d69eab2014-05-17 16:59:31 +0800295 :raises TypeError: This exception is raised if ``key_material`` is not
Ayrx00eff9c2014-05-17 19:47:09 +0800296 ``bytes``.
Ayrxc48100a2014-05-10 13:01:46 +0800297
Ayrx9d72f122014-05-06 20:27:51 +0800298 Derives a new key from the input key material by performing both the
299 extract and expand operations.
300
301 .. method:: verify(key_material, expected_key)
302
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600303 :param bytes key_material: The input key material. This is the same as
Ayrx9d72f122014-05-06 20:27:51 +0800304 ``key_material`` in :meth:`derive`.
Alex Gaynor1cfc5d52014-11-23 17:44:28 -0600305 :param bytes expected_key: The expected result of deriving a new key,
Ayrx9d72f122014-05-06 20:27:51 +0800306 this is the same as the return value of
307 :meth:`derive`.
308 :raises cryptography.exceptions.InvalidKey: This is raised when the
309 derived key does not match
310 the expected key.
311 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
312 :meth:`derive` or
313 :meth:`verify` is
314 called more than
315 once.
Ayrxc48100a2014-05-10 13:01:46 +0800316 :raises TypeError: This is raised if the provided ``key_material`` is
317 a unicode object
Ayrx9d72f122014-05-06 20:27:51 +0800318
319 This checks whether deriving a new key from the supplied
320 ``key_material`` generates the same key as the ``expected_key``, and
321 raises an exception if they do not match.
322
Simo Sorce8a690fb2015-05-01 15:56:30 -0400323.. currentmodule:: cryptography.hazmat.primitives.kdf.concatkdf
324
325.. class:: ConcatKDFHash(algorithm, length, otherinfo, backend)
326
327 .. versionadded:: 1.0
328
329 ConcatKDFHash (Concatenation Key Derivation Function) is defined by the
330 NIST Special Publication `NIST SP 800-56Ar2`_ document, to be used to
331 derive keys for use after a Key Exchange negotiation operation.
332
333 .. warning::
334
335 ConcatKDFHash should not be used for password storage.
336
337 .. doctest::
338
339 >>> import os
340 >>> from cryptography.hazmat.primitives import hashes
341 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
342 >>> from cryptography.hazmat.backends import default_backend
343 >>> backend = default_backend()
Simo Sorce8a690fb2015-05-01 15:56:30 -0400344 >>> otherinfo = b"concatkdf-example"
345 >>> ckdf = ConcatKDFHash(
346 ... algorithm=hashes.SHA256(),
347 ... length=256,
348 ... otherinfo=otherinfo,
349 ... backend=backend
350 ... )
351 >>> key = ckdf.derive(b"input key")
352 >>> ckdf = ConcatKDFHash(
353 ... algorithm=hashes.SHA256(),
354 ... length=256,
355 ... otherinfo=otherinfo,
356 ... backend=backend
357 ... )
358 >>> ckdf.verify(b"input key", key)
359
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300360 :param algorithm: An instance of
361 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400362
363 :param int length: The desired length of the derived key in bytes.
364 Maximum is ``hashlen * (2^32 -1)``.
365
366 :param bytes otherinfo: Application specific context information.
367 If ``None`` is explicitly passed an empty byte string will be used.
368
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300369 :param backend: An instance of
370 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400371
372 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
373 if the provided ``backend`` does not implement
374 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
375
376 :raises TypeError: This exception is raised if ``otherinfo`` is not
377 ``bytes``.
378
379 .. method:: derive(key_material)
380
381 :param bytes key_material: The input key material.
382 :return bytes: The derived key.
383 :raises TypeError: This exception is raised if ``key_material`` is
384 not ``bytes``.
385
Terry Chiadae40762015-06-13 11:26:16 +0800386 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400387
388 .. method:: verify(key_material, expected_key)
389
390 :param bytes key_material: The input key material. This is the same as
391 ``key_material`` in :meth:`derive`.
392 :param bytes expected_key: The expected result of deriving a new key,
393 this is the same as the return value of
394 :meth:`derive`.
395 :raises cryptography.exceptions.InvalidKey: This is raised when the
396 derived key does not match
397 the expected key.
398 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
399 :meth:`derive` or
400 :meth:`verify` is
401 called more than
402 once.
403
404 This checks whether deriving a new key from the supplied
405 ``key_material`` generates the same key as the ``expected_key``, and
406 raises an exception if they do not match.
407
408
409.. class:: ConcatKDFHMAC(algorithm, length, salt, otherinfo, backend)
410
411 .. versionadded:: 1.0
412
413 Similar to ConcatKFDHash but uses an HMAC function instead.
414
415 .. warning::
416
417 ConcatKDFHMAC should not be used for password storage.
418
419 .. doctest::
420
421 >>> import os
422 >>> from cryptography.hazmat.primitives import hashes
423 >>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC
424 >>> from cryptography.hazmat.backends import default_backend
425 >>> backend = default_backend()
426 >>> salt = os.urandom(16)
427 >>> otherinfo = b"concatkdf-example"
428 >>> ckdf = ConcatKDFHMAC(
429 ... algorithm=hashes.SHA256(),
430 ... length=256,
431 ... salt=salt,
432 ... otherinfo=otherinfo,
433 ... backend=backend
434 ... )
435 >>> key = ckdf.derive(b"input key")
436 >>> ckdf = ConcatKDFHMAC(
437 ... algorithm=hashes.SHA256(),
438 ... length=256,
439 ... salt=salt,
440 ... otherinfo=otherinfo,
441 ... backend=backend
442 ... )
443 >>> ckdf.verify(b"input key", key)
444
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300445 :param algorithm: An instance of
446 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400447
448 :param int length: The desired length of the derived key in bytes. Maximum
449 is ``hashlen * (2^32 -1)``.
450
451 :param bytes salt: A salt. Randomizes the KDF's output. Optional, but
452 highly recommended. Ideally as many bits of entropy as the security
453 level of the hash: often that means cryptographically random and as
454 long as the hash output. Does not have to be secret, but may cause
455 stronger security guarantees if secret; If ``None`` is explicitly
456 passed a default salt of ``algorithm.block_size`` null bytes will be
457 used.
458
459 :param bytes otherinfo: Application specific context information.
460 If ``None`` is explicitly passed an empty byte string will be used.
461
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300462 :param backend: An instance of
463 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400464
465 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
466 provided ``backend`` does not implement
467 :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
468
469 :raises TypeError: This exception is raised if ``salt`` or ``otherinfo``
470 is not ``bytes``.
471
472 .. method:: derive(key_material)
473
474 :param bytes key_material: The input key material.
475 :return bytes: The derived key.
476 :raises TypeError: This exception is raised if ``key_material`` is not
477 ``bytes``.
478
Terry Chiadae40762015-06-13 11:26:16 +0800479 Derives a new key from the input key material.
Simo Sorce8a690fb2015-05-01 15:56:30 -0400480
481 .. method:: verify(key_material, expected_key)
482
483 :param bytes key_material: The input key material. This is the same as
484 ``key_material`` in :meth:`derive`.
485 :param bytes expected_key: The expected result of deriving a new key,
486 this is the same as the return value of
487 :meth:`derive`.
488 :raises cryptography.exceptions.InvalidKey: This is raised when the
489 derived key does not match
490 the expected key.
491 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
492 :meth:`derive` or
493 :meth:`verify` is
494 called more than
495 once.
496
497 This checks whether deriving a new key from the supplied
498 ``key_material`` generates the same key as the ``expected_key``, and
499 raises an exception if they do not match.
500
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400501.. currentmodule:: cryptography.hazmat.primitives.kdf.x963kdf
502
503.. class:: X963KDF(algorithm, length, otherinfo, backend)
504
505 .. versionadded:: 1.1
506
507 X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI
508 in the `ANSI X9.63:2001`_ document, to be used to derive keys for use
509 after a Key Exchange negotiation operation.
510
511 SECG in `SEC 1 v2.0`_ recommends that
512 :class:`~cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash` be
513 used for new projects. This KDF should only be used for backwards
Alex Gaynorace036d2015-09-24 20:23:08 -0400514 compatibility with pre-existing protocols.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400515
516
517 .. warning::
518
519 X963KDF should not be used for password storage.
520
521 .. doctest::
522
523 >>> import os
524 >>> from cryptography.hazmat.primitives import hashes
525 >>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
526 >>> from cryptography.hazmat.backends import default_backend
527 >>> backend = default_backend()
528 >>> sharedinfo = b"ANSI X9.63 Example"
529 >>> xkdf = X963KDF(
530 ... algorithm=hashes.SHA256(),
531 ... length=256,
532 ... sharedinfo=sharedinfo,
533 ... backend=backend
534 ... )
535 >>> key = xkdf.derive(b"input key")
536 >>> xkdf = X963KDF(
537 ... algorithm=hashes.SHA256(),
538 ... length=256,
539 ... sharedinfo=sharedinfo,
540 ... backend=backend
541 ... )
542 >>> xkdf.verify(b"input key", key)
543
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300544 :param algorithm: An instance of
545 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400546
547 :param int length: The desired length of the derived key in bytes.
548 Maximum is ``hashlen * (2^32 -1)``.
549
550 :param bytes sharedinfo: Application specific context information.
551 If ``None`` is explicitly passed an empty byte string will be used.
552
553 :param backend: A cryptography backend
554 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300555 instance.
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400556
557 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
558 if the provided ``backend`` does not implement
559 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
560
561 :raises TypeError: This exception is raised if ``sharedinfo`` is not
562 ``bytes``.
563
564 .. method:: derive(key_material)
565
566 :param bytes key_material: The input key material.
567 :return bytes: The derived key.
568 :raises TypeError: This exception is raised if ``key_material`` is
569 not ``bytes``.
570
571 Derives a new key from the input key material.
572
573 .. method:: verify(key_material, expected_key)
574
575 :param bytes key_material: The input key material. This is the same as
576 ``key_material`` in :meth:`derive`.
577 :param bytes expected_key: The expected result of deriving a new key,
578 this is the same as the return value of
579 :meth:`derive`.
580 :raises cryptography.exceptions.InvalidKey: This is raised when the
581 derived key does not match
582 the expected key.
583 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
584 :meth:`derive` or
585 :meth:`verify` is
586 called more than
587 once.
588
589 This checks whether deriving a new key from the supplied
590 ``key_material`` generates the same key as the ``expected_key``, and
591 raises an exception if they do not match.
592
Simo Sorce8a690fb2015-05-01 15:56:30 -0400593
Jared6d7fe002016-05-29 17:32:37 -0700594.. currentmodule:: cryptography.hazmat.primitives.kdf.kbkdf
595
596.. class:: KBKDFHMAC(algorithm, mode, length, rlen, llen, location,\
597 label, context, fixed, backend)
598
599 .. versionadded:: 1.4
600
601 KBKDF (Key Based Key Derivation Function) is defined by the
602 `NIST SP 800-108`_ document, to be used to derive additional
603 keys from a key that has been established through an automated
604 key-establishment scheme.
605
606 .. warning::
607
608 KBKDFHMAC should not be used for password storage.
609
610 .. doctest::
611
612 >>> import os
613 >>> from cryptography.hazmat.primitives import hashes
614 >>> from cryptography.hazmat.primitives.kdf.kbkdf import (
615 ... CounterLocation, KBKDFHMAC, Mode
616 ... )
617 >>> from cryptography.hazmat.backends import default_backend
618 >>> backend = default_backend()
619 >>> label = b"KBKDF HMAC Label"
620 >>> context = b"KBKDF HMAC Context"
621 >>> kdf = KBKDFHMAC(
622 ... algorithm=hashes.SHA256(),
623 ... mode=Mode.CounterMode,
624 ... length=256,
625 ... rlen=4,
626 ... llen=4,
627 ... location=CounterLocation.BeforeFixed,
628 ... label=label,
629 ... context=context,
630 ... fixed=None,
631 ... backend=backend
632 ... )
633 >>> key = kdf.derive(b"input key")
634 >>> kdf = KBKDFHMAC(
635 ... algorithm=hashes.SHA256(),
636 ... mode=Mode.CounterMode,
637 ... length=256,
638 ... rlen=4,
639 ... llen=4,
640 ... location=CounterLocation.BeforeFixed,
641 ... label=label,
642 ... context=context,
643 ... fixed=None,
644 ... backend=backend
645 ... )
646 >>> kdf.verify(b"input key", key)
647
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300648 :param algorithm: An instance of
649 :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`.
Jared6d7fe002016-05-29 17:32:37 -0700650
651 :param mode: The desired mode of the PRF. A value from the
652 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.Mode` enum.
653
654 :param int length: The desired length of the derived key in bytes.
655
656 :param int rlen: An integer that indicates the length of the binary
657 representation of the counter in bytes.
658
659 :param int llen: An integer that indicates the binary
660 representation of the ``length`` in bytes.
661
662 :param location: The desired location of the counter. A value from the
663 :class:`~cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation` enum.
664
665 :param bytes label: Application specific label information. If ``None``
666 is explicitly passed an empty byte string will be used.
667
668 :param bytes context: Application specific context information. If ``None``
669 is explicitly passed an empty byte string will be used.
670
671 :param bytes fixed: Instead of specifying ``label`` and ``context`` you
672 may supply your own fixed data. If ``fixed`` is specified, ``label``
673 and ``context`` is ignored.
674
675 :param backend: A cryptography backend
676 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300677 instance.
Jared6d7fe002016-05-29 17:32:37 -0700678
679 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised
680 if the provided ``backend`` does not implement
681 :class:`~cryptography.hazmat.backends.interfaces.HashBackend`
682
683 :raises TypeError: This exception is raised if ``label`` or ``context``
684 is not ``bytes``. Also raised if ``rlen`` or ``llen`` is not ``int``.
685
686 :raises ValueError: This exception is raised if ``rlen`` or ``llen``
687 is greater than 4 or less than 1. This exception is also raised if
688 you specify a ``label`` or ``context`` and ``fixed``.
689
690 .. method:: derive(key_material)
691
692 :param bytes key_material: The input key material.
693 :return bytes: The derived key.
694 :raises TypeError: This exception is raised if ``key_material`` is
695 not ``bytes``.
696
697 Derives a new key from the input key material.
698
699 .. method:: verify(key_material, expected_key)
700
701 :param bytes key_material: The input key material. This is the same as
702 ``key_material`` in :meth:`derive`.
703 :param bytes expected_key: The expected result of deriving a new key,
704 this is the same as the return value of
705 :meth:`derive`.
706 :raises cryptography.exceptions.InvalidKey: This is raised when the
707 derived key does not match
708 the expected key.
709 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
710 :meth:`derive` or
711 :meth:`verify` is
712 called more than
713 once.
714
715 This checks whether deriving a new key from the supplied
716 ``key_material`` generates the same key as the ``expected_key``, and
717 raises an exception if they do not match.
718
719.. class:: Mode
720
721 An enumeration for the key based key derivative modes.
722
723 .. attribute:: CounterMode
724
725 The output of the PRF is computed with a counter
726 as the iteration variable.
727
728.. class:: CounterLocation
729
730 An enumeration for the key based key derivative counter location.
731
732 .. attribute:: BeforeFixed
733
734 The counter iteration variable will be concatenated before
735 the fixed input data.
736
737 .. attribute:: AfterFixed
738
739 The counter iteration variable will be concatenated after
740 the fixed input data.
741
Terry Chiad8a27df2016-09-01 23:39:57 +0800742.. currentmodule:: cryptography.hazmat.primitives.kdf.scrypt
743
744.. class:: Scrypt(salt, length, n, r, p, backend)
745
746 .. versionadded:: 1.6
747
748 Scrypt is a KDF designed for password storage by Colin Percival to be
749 resistant against hardware-assisted attackers by having a tunable memory
750 cost. It is described in :rfc:`7914`.
751
752 This class conforms to the
753 :class:`~cryptography.hazmat.primitives.kdf.KeyDerivationFunction`
754 interface.
755
756 .. code-block:: python
757
758 >>> import os
Terry Chiad8a27df2016-09-01 23:39:57 +0800759 >>> 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,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800767 ... n=2**14,
Terry Chiad8a27df2016-09-01 23:39:57 +0800768 ... r=8,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800769 ... p=1,
Terry Chiad8a27df2016-09-01 23:39:57 +0800770 ... backend=backend
771 ... )
772 >>> key = kdf.derive(b"my great password")
773 >>> # verify
774 >>> kdf = Scrypt(
775 ... salt=salt,
776 ... length=64,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800777 ... n=2**14,
Terry Chiad8a27df2016-09-01 23:39:57 +0800778 ... r=8,
Nick Badgeracaf89d2016-12-10 17:41:50 -0800779 ... p=1,
Terry Chiad8a27df2016-09-01 23:39:57 +0800780 ... 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
Nick Badgeracaf89d2016-12-10 17:41:50 -0800792 the 3 parameters: ``n``, ``r``, and ``p``. In general, the memory cost of
793 Scrypt is affected by the values of both ``n`` and ``r``, while ``n`` also
794 determines the number of iterations performed. ``p`` increases the
795 computational cost without affecting memory usage. A more in-depth
796 explanation of the 3 parameters can be found `here`_.
Terry Chiad8a27df2016-09-01 23:39:57 +0800797
Nick Badgeracaf89d2016-12-10 17:41:50 -0800798 :rfc:`7914` `recommends`_ values of ``r=8`` and ``p=1`` while scaling ``n``
799 to a number appropriate for your system. `The scrypt paper`_ suggests a
800 minimum value of ``n=2**14`` for interactive logins (t < 100ms), or
801 ``n=2**20`` for more sensitive files (t < 5s).
Terry Chiad8a27df2016-09-01 23:39:57 +0800802
803 :param backend: An instance of
804 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`.
805
806 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
807 provided ``backend`` does not implement
808 :class:`~cryptography.hazmat.backends.interfaces.ScryptBackend`
809
810 :raises TypeError: This exception is raised if ``salt`` is not ``bytes``.
Terry Chiaa2d0da92016-09-03 07:57:45 +0800811 :raises ValueError: This exception is raised if ``n`` is less than 2, if
812 ``n`` is not a power of 2, if ``r`` is less than 1 or if ``p`` is less
813 than 1.
Terry Chiad8a27df2016-09-01 23:39:57 +0800814
815 .. method:: derive(key_material)
816
817 :param bytes key_material: The input key material.
818 :return bytes: the derived key.
819 :raises TypeError: This exception is raised if ``key_material`` is not
820 ``bytes``.
821 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
822 :meth:`derive` or
823 :meth:`verify` is
824 called more than
825 once.
826
827 This generates and returns a new key from the supplied password.
828
829 .. method:: verify(key_material, expected_key)
830
831 :param bytes key_material: The input key material. This is the same as
832 ``key_material`` in :meth:`derive`.
833 :param bytes expected_key: The expected result of deriving a new key,
834 this is the same as the return value of
835 :meth:`derive`.
836 :raises cryptography.exceptions.InvalidKey: This is raised when the
837 derived key does not match
838 the expected key.
839 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
840 :meth:`derive` or
841 :meth:`verify` is
842 called more than
843 once.
844
845 This checks whether deriving a new key from the supplied
846 ``key_material`` generates the same key as the ``expected_key``, and
847 raises an exception if they do not match. This can be used for
848 checking whether the password a user provides matches the stored derived
849 key.
850
Paul Kehrer48402ff2015-02-16 15:31:52 -0600851Interface
852~~~~~~~~~
853
854.. currentmodule:: cryptography.hazmat.primitives.kdf
855
856.. class:: KeyDerivationFunction
857
858 .. versionadded:: 0.2
859
860 .. method:: derive(key_material)
861
862 :param bytes key_material: The input key material. Depending on what
863 key derivation function you are using this
864 could be either random bytes, or a user
865 supplied password.
866 :return: The new key.
867 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
868 :meth:`derive` or
869 :meth:`verify` is
870 called more than
871 once.
872
873 This generates and returns a new key from the supplied key material.
874
875 .. method:: verify(key_material, expected_key)
876
877 :param bytes key_material: The input key material. This is the same as
878 ``key_material`` in :meth:`derive`.
879 :param bytes expected_key: The expected result of deriving a new key,
880 this is the same as the return value of
881 :meth:`derive`.
882 :raises cryptography.exceptions.InvalidKey: This is raised when the
883 derived key does not match
884 the expected key.
885 :raises cryptography.exceptions.AlreadyFinalized: This is raised when
886 :meth:`derive` or
887 :meth:`verify` is
888 called more than
889 once.
890
891 This checks whether deriving a new key from the supplied
892 ``key_material`` generates the same key as the ``expected_key``, and
893 raises an exception if they do not match. This can be used for
894 something like checking whether a user's password attempt matches the
895 stored derived key.
896
897
Cory Benfield9b22eb92017-05-22 22:40:40 -0700898.. [#nist] See `NIST SP 800-132`_.
899
Alex Gaynor64f1f422017-02-27 22:25:37 -0500900.. _`NIST SP 800-132`: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
901.. _`NIST SP 800-108`: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-108.pdf
Simo Sorce8a690fb2015-05-01 15:56:30 -0400902.. _`NIST SP 800-56Ar2`: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
Simo Sorce53c8f6a2015-09-15 11:13:56 -0400903.. _`ANSI X9.63:2001`: https://webstore.ansi.org
904.. _`SEC 1 v2.0`: http://www.secg.org/sec1-v2.pdf
Paul Kehrerb3f763f2014-01-28 16:42:15 -0600905.. _`Password Storage Cheat Sheet`: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
David Reidb80deea2014-02-03 10:33:16 -0800906.. _`PBKDF2`: https://en.wikipedia.org/wiki/PBKDF2
David Reidb80deea2014-02-03 10:33:16 -0800907.. _`key stretching`: https://en.wikipedia.org/wiki/Key_stretching
Alex Gaynor2e8725d2016-08-29 21:40:19 -0400908.. _`HKDF`: https://en.wikipedia.org/wiki/HKDF
David Reidb80deea2014-02-03 10:33:16 -0800909.. _`HKDF paper`: https://eprint.iacr.org/2010/264
Terry Chiad8a27df2016-09-01 23:39:57 +0800910.. _`here`: https://stackoverflow.com/a/30308723/1170681
911.. _`recommends`: https://tools.ietf.org/html/rfc7914#section-2
Nick Badgeracaf89d2016-12-10 17:41:50 -0800912.. _`The scrypt paper`: https://www.tarsnap.com/scrypt/scrypt.pdf