Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 1 | .. danger:: |
| 2 | |
| 3 | This is a "Hazardous Materials" module. You should **ONLY** use it if |
| 4 | you're 100% absolutely sure that you know what you're doing because this |
| 5 | module is full of land mines, dragons, and dinosaurs with laser guns. |
| 6 | |
| 7 | |
| 8 | Hash-based Message Authentication Codes |
| 9 | ======================================= |
| 10 | |
Alex Gaynor | 4658ce1 | 2013-10-29 15:26:50 -0700 | [diff] [blame] | 11 | .. currentmodule:: cryptography.hazmat.primitives.hmac |
| 12 | |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 13 | .. testsetup:: |
| 14 | |
| 15 | import binascii |
| 16 | key = binascii.unhexlify(b"0" * 32) |
| 17 | |
| 18 | Hash-based message authentication codes (or HMACs) are a tool for calculating |
| 19 | message authentication codes using a cryptographic hash function coupled with a |
| 20 | secret key. You can use an HMAC to verify integrity as well as authenticate a |
| 21 | message. |
| 22 | |
Alex Gaynor | 4658ce1 | 2013-10-29 15:26:50 -0700 | [diff] [blame] | 23 | .. class:: HMAC(key, msg=None, digestmod=None) |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 24 | |
Paul Kehrer | ca8ed29 | 2013-10-28 19:37:39 -0500 | [diff] [blame] | 25 | HMAC objects take a ``key``, a hash class derived from |
Paul Kehrer | 50a8815 | 2013-10-29 10:46:05 -0500 | [diff] [blame] | 26 | :class:`~cryptography.primitives.hashes.BaseHash`, and optional message. |
| 27 | The ``key`` should be randomly generated bytes and is recommended to be |
| 28 | equal in length to the ``digest_size`` of the hash function chosen. |
| 29 | You must keep the ``key`` secret. |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 30 | |
| 31 | .. doctest:: |
| 32 | |
Paul Kehrer | bf8962a | 2013-10-28 17:44:42 -0500 | [diff] [blame] | 33 | >>> from cryptography.hazmat.primitives import hashes, hmac |
Paul Kehrer | 2824ab7 | 2013-10-28 11:06:55 -0500 | [diff] [blame] | 34 | >>> h = hmac.HMAC(key, digestmod=hashes.SHA256) |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 35 | >>> h.update(b"message to hash") |
| 36 | >>> h.hexdigest() |
| 37 | '...' |
| 38 | |
Paul Kehrer | 2824ab7 | 2013-10-28 11:06:55 -0500 | [diff] [blame] | 39 | .. method:: update(msg) |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 40 | |
Paul Kehrer | 50a8815 | 2013-10-29 10:46:05 -0500 | [diff] [blame] | 41 | :param bytes msg: The bytes to hash and authenticate. |
Paul Kehrer | 0317b04 | 2013-10-28 17:34:27 -0500 | [diff] [blame] | 42 | |
| 43 | .. method:: copy() |
| 44 | |
| 45 | :return: a new instance of this object with a copied internal state. |
| 46 | |
| 47 | .. method:: digest() |
| 48 | |
| 49 | :return bytes: The message digest as bytes. |
| 50 | |
| 51 | .. method:: hexdigest() |
| 52 | |
| 53 | :return str: The message digest as hex. |
| 54 | |