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