blob: 44cc29fac66af03eeb4ecd31245f306e02ef964a [file] [log] [blame]
Alex Gaynoraf82d5e2013-10-29 17:07:24 -07001.. hazmat::
Paul Kehrer0317b042013-10-28 17:34:27 -05002
3Hash-based Message Authentication Codes
4=======================================
5
Alex Gaynor4658ce12013-10-29 15:26:50 -07006.. currentmodule:: cryptography.hazmat.primitives.hmac
7
Paul Kehrer0317b042013-10-28 17:34:27 -05008.. testsetup::
9
10 import binascii
11 key = binascii.unhexlify(b"0" * 32)
12
13Hash-based message authentication codes (or HMACs) are a tool for calculating
14message authentication codes using a cryptographic hash function coupled with a
15secret key. You can use an HMAC to verify integrity as well as authenticate a
16message.
17
Alex Gaynor4658ce12013-10-29 15:26:50 -070018.. class:: HMAC(key, msg=None, digestmod=None)
Paul Kehrer0317b042013-10-28 17:34:27 -050019
Paul Kehrerca8ed292013-10-28 19:37:39 -050020 HMAC objects take a ``key``, a hash class derived from
Paul Kehrer50a88152013-10-29 10:46:05 -050021 :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 Kehrer0317b042013-10-28 17:34:27 -050025
26 .. doctest::
27
Paul Kehrerbf8962a2013-10-28 17:44:42 -050028 >>> from cryptography.hazmat.primitives import hashes, hmac
Paul Kehrer2824ab72013-10-28 11:06:55 -050029 >>> h = hmac.HMAC(key, digestmod=hashes.SHA256)
Paul Kehrer0317b042013-10-28 17:34:27 -050030 >>> h.update(b"message to hash")
31 >>> h.hexdigest()
32 '...'
33
Paul Kehrer2824ab72013-10-28 11:06:55 -050034 .. method:: update(msg)
Paul Kehrer0317b042013-10-28 17:34:27 -050035
Paul Kehrer50a88152013-10-29 10:46:05 -050036 :param bytes msg: The bytes to hash and authenticate.
Paul Kehrer0317b042013-10-28 17:34:27 -050037
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