blob: bfbe325579b300f86bf354dc75b3e245beb6d30b [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
Paul Kehrer50a88152013-10-29 10:46:05 -050024 :class:`~cryptography.primitives.hashes.BaseHash`, and optional message.
25 The ``key`` should be randomly generated bytes and is recommended to be
26 equal in length to the ``digest_size`` of the hash function chosen.
27 You must keep the ``key`` secret.
Paul Kehrer0317b042013-10-28 17:34:27 -050028
29 .. doctest::
30
Paul Kehrerbf8962a2013-10-28 17:44:42 -050031 >>> from cryptography.hazmat.primitives import hashes, hmac
Paul Kehrer2824ab72013-10-28 11:06:55 -050032 >>> h = hmac.HMAC(key, digestmod=hashes.SHA256)
Paul Kehrer0317b042013-10-28 17:34:27 -050033 >>> h.update(b"message to hash")
34 >>> h.hexdigest()
35 '...'
36
Paul Kehrer2824ab72013-10-28 11:06:55 -050037 .. method:: update(msg)
Paul Kehrer0317b042013-10-28 17:34:27 -050038
Paul Kehrer50a88152013-10-29 10:46:05 -050039 :param bytes msg: The bytes to hash and authenticate.
Paul Kehrer0317b042013-10-28 17:34:27 -050040
41 .. method:: copy()
42
43 :return: a new instance of this object with a copied internal state.
44
45 .. method:: digest()
46
47 :return bytes: The message digest as bytes.
48
49 .. method:: hexdigest()
50
51 :return str: The message digest as hex.
52