blob: aec406b9d45e6296e011874b0c1fa8f6214cc311 [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
Paul Kehrerca8ed292013-10-28 19:37:39 -050023 HMAC objects take a ``key``, a hash class derived from
24 :class:`~cryptography.primitives.hashes.BaseHash`, and optional msg. The
25 ``key`` should be randomly generated bytes and the length of the
26 ``block_size`` of the hash. You must keep the ``key`` secret.
Paul Kehrer0317b042013-10-28 17:34:27 -050027
28 .. doctest::
29
Paul Kehrerbf8962a2013-10-28 17:44:42 -050030 >>> from cryptography.hazmat.primitives import hashes, hmac
Paul Kehrer2824ab72013-10-28 11:06:55 -050031 >>> h = hmac.HMAC(key, digestmod=hashes.SHA256)
Paul Kehrer0317b042013-10-28 17:34:27 -050032 >>> h.update(b"message to hash")
33 >>> h.hexdigest()
34 '...'
35
Paul Kehrer2824ab72013-10-28 11:06:55 -050036 .. method:: update(msg)
Paul Kehrer0317b042013-10-28 17:34:27 -050037
Paul Kehrer30eabdd2013-10-28 12:52:47 -050038 :param bytes msg: The bytes you wish to hash.
Paul Kehrer0317b042013-10-28 17:34:27 -050039
40 .. method:: copy()
41
42 :return: a new instance of this object with a copied internal state.
43
44 .. method:: digest()
45
46 :return bytes: The message digest as bytes.
47
48 .. method:: hexdigest()
49
50 :return str: The message digest as hex.
51