Julian Krause | 9c3088f | 2013-12-04 14:49:50 -0800 | [diff] [blame] | 1 | .. hazmat:: |
| 2 | |
| 3 | Constant time functions |
| 4 | ======================= |
| 5 | |
| 6 | .. currentmodule:: cryptography.hazmat.primitives.constant_time |
| 7 | |
Julian Krause | 848f770 | 2013-12-12 20:55:39 -0800 | [diff] [blame] | 8 | This module contains functions for operating with secret data in a way that |
| 9 | does not leak information about that data through how long it takes to perform |
| 10 | the operation. These functions should be used whenever operating on secret data |
| 11 | along with data that is user supplied. |
Julian Krause | d6f14da | 2013-12-05 11:06:27 -0800 | [diff] [blame] | 12 | |
Julian Krause | 848f770 | 2013-12-12 20:55:39 -0800 | [diff] [blame] | 13 | An example would be comparing a HMAC signature received from a client to the |
| 14 | one generated by the server code for authentication purposes. |
| 15 | |
| 16 | For more information about this sort of issue, see `Coda Hale's blog post`_ |
Julian Krause | 383a04c | 2013-12-13 23:47:17 -0800 | [diff] [blame] | 17 | about the timing attacks on KeyCzar and Java's ``MessageDigest.isEqual()``. |
Julian Krause | d6f14da | 2013-12-05 11:06:27 -0800 | [diff] [blame] | 18 | |
Julian Krause | 9c3088f | 2013-12-04 14:49:50 -0800 | [diff] [blame] | 19 | |
| 20 | .. function:: bytes_eq(a, b) |
| 21 | |
Alex Gaynor | ae9451f | 2014-02-04 17:16:37 -0800 | [diff] [blame] | 22 | 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 Krause | 9c3088f | 2013-12-04 14:49:50 -0800 | [diff] [blame] | 26 | |
| 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 | |
Alex Gaynor | e6c41b0 | 2014-02-04 17:19:52 -0800 | [diff] [blame^] | 35 | :param bytes a: The left-hand side. |
| 36 | :param bytes b: The right-hand side. |
| 37 | :returns bool: ``True`` if ``a`` has the same bytes as ``b``, otherwise |
| 38 | ``False``. |
Julian Krause | d6f14da | 2013-12-05 11:06:27 -0800 | [diff] [blame] | 39 | |
| 40 | |
Julian Krause | 848f770 | 2013-12-12 20:55:39 -0800 | [diff] [blame] | 41 | .. _`Coda Hale's blog post`: http://codahale.com/a-lesson-in-timing-attacks/ |