blob: 702df2c7fb53c68f1e74319f4fb6323bc015a2f4 [file] [log] [blame]
Paul Kehrer0317b042013-10-28 17:34:27 -05001.. 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
8Hash-based Message Authentication Codes
9=======================================
10
11.. testsetup::
12
13 import binascii
14 key = binascii.unhexlify(b"0" * 32)
15
16Hash-based message authentication codes (or HMACs) are a tool for calculating
17message authentication codes using a cryptographic hash function coupled with a
18secret key. You can use an HMAC to verify integrity as well as authenticate a
19message.
20
Paul Kehrerbf8962a2013-10-28 17:44:42 -050021.. class:: cryptography.hazmat.primitives.hmac.HMAC(key, msg=None, digestmod=None)
Paul Kehrer0317b042013-10-28 17:34:27 -050022
23 HMAC objects take a ``key``, a hash class derived from :class:`~cryptography.primitives.hashes.BaseHash`,
Paul Kehrer2824ab72013-10-28 11:06:55 -050024 and optional msg. The ``key`` should be randomly generated bytes and
Paul Kehrer0317b042013-10-28 17:34:27 -050025 the length of the ``block_size`` of the hash. You must keep the ``key`` secret.
26
27 .. doctest::
28
Paul Kehrerbf8962a2013-10-28 17:44:42 -050029 >>> from cryptography.hazmat.primitives import hashes, hmac
Paul Kehrer2824ab72013-10-28 11:06:55 -050030 >>> h = hmac.HMAC(key, digestmod=hashes.SHA256)
Paul Kehrer0317b042013-10-28 17:34:27 -050031 >>> h.update(b"message to hash")
32 >>> h.hexdigest()
33 '...'
34
Paul Kehrer2824ab72013-10-28 11:06:55 -050035 .. method:: update(msg)
Paul Kehrer0317b042013-10-28 17:34:27 -050036
Paul Kehrer30eabdd2013-10-28 12:52:47 -050037 :param bytes msg: The bytes you wish to hash.
Paul Kehrer0317b042013-10-28 17:34:27 -050038
39 .. method:: copy()
40
41 :return: a new instance of this object with a copied internal state.
42
43 .. method:: digest()
44
45 :return bytes: The message digest as bytes.
46
47 .. method:: hexdigest()
48
49 :return str: The message digest as hex.
50