blob: 7924efcaa8db8450764176ec60d3203a9ab17a78 [file] [log] [blame]
Julian Krause9c3088f2013-12-04 14:49:50 -08001.. hazmat::
2
3Constant time functions
4=======================
5
6.. currentmodule:: cryptography.hazmat.primitives.constant_time
7
Julian Krause848f7702013-12-12 20:55:39 -08008This module contains functions for operating with secret data in a way that
9does not leak information about that data through how long it takes to perform
10the operation. These functions should be used whenever operating on secret data
11along with data that is user supplied.
Julian Kraused6f14da2013-12-05 11:06:27 -080012
Julian Krause848f7702013-12-12 20:55:39 -080013An example would be comparing a HMAC signature received from a client to the
14one generated by the server code for authentication purposes.
15
16For more information about this sort of issue, see `Coda Hale's blog post`_
Julian Krause383a04c2013-12-13 23:47:17 -080017about the timing attacks on KeyCzar and Java's ``MessageDigest.isEqual()``.
Julian Kraused6f14da2013-12-05 11:06:27 -080018
Julian Krause9c3088f2013-12-04 14:49:50 -080019
20.. function:: bytes_eq(a, b)
21
Alex Gaynorae9451f2014-02-04 17:16:37 -080022 Compares ``a`` and ``b`` with one another. If ``a`` and ``b`` have
23 different lengths, this returns ``False`` immediately. Otherwise it
24 compares them in a way that takes the same amount of time, regardless of
25 how many characters are the same between the two.
Julian Krause9c3088f2013-12-04 14:49:50 -080026
27 .. doctest::
28
29 >>> from cryptography.hazmat.primitives import constant_time
30 >>> constant_time.bytes_eq(b"foo", b"foo")
31 True
32 >>> constant_time.bytes_eq(b"foo", b"bar")
33 False
34
Julian Kraused6f14da2013-12-05 11:06:27 -080035 :param a bytes: The left-hand side.
36 :param b bytes: The right-hand side.
37 :returns boolean: True if ``a`` has the same bytes as ``b``.
38
39
Julian Krause848f7702013-12-12 20:55:39 -080040.. _`Coda Hale's blog post`: http://codahale.com/a-lesson-in-timing-attacks/