blob: e66de36fbf1b843e8154a3174ad9390378992668 [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
Alex Gaynor4658ce12013-10-29 15:26:50 -070011.. currentmodule:: cryptography.hazmat.primitives.hmac
12
Paul Kehrer0317b042013-10-28 17:34:27 -050013.. testsetup::
14
15 import binascii
16 key = binascii.unhexlify(b"0" * 32)
17
18Hash-based message authentication codes (or HMACs) are a tool for calculating
19message authentication codes using a cryptographic hash function coupled with a
20secret key. You can use an HMAC to verify integrity as well as authenticate a
21message.
22
Alex Gaynor4658ce12013-10-29 15:26:50 -070023.. class:: HMAC(key, msg=None, digestmod=None)
Paul Kehrer0317b042013-10-28 17:34:27 -050024
Paul Kehrerca8ed292013-10-28 19:37:39 -050025 HMAC objects take a ``key``, a hash class derived from
Paul Kehrer50a88152013-10-29 10:46:05 -050026 :class:`~cryptography.primitives.hashes.BaseHash`, and optional message.
27 The ``key`` should be randomly generated bytes and is recommended to be
28 equal in length to the ``digest_size`` of the hash function chosen.
29 You must keep the ``key`` secret.
Paul Kehrer0317b042013-10-28 17:34:27 -050030
31 .. doctest::
32
Paul Kehrerbf8962a2013-10-28 17:44:42 -050033 >>> from cryptography.hazmat.primitives import hashes, hmac
Paul Kehrer2824ab72013-10-28 11:06:55 -050034 >>> h = hmac.HMAC(key, digestmod=hashes.SHA256)
Paul Kehrer0317b042013-10-28 17:34:27 -050035 >>> h.update(b"message to hash")
36 >>> h.hexdigest()
37 '...'
38
Paul Kehrer2824ab72013-10-28 11:06:55 -050039 .. method:: update(msg)
Paul Kehrer0317b042013-10-28 17:34:27 -050040
Paul Kehrer50a88152013-10-29 10:46:05 -050041 :param bytes msg: The bytes to hash and authenticate.
Paul Kehrer0317b042013-10-28 17:34:27 -050042
43 .. method:: copy()
44
45 :return: a new instance of this object with a copied internal state.
46
47 .. method:: digest()
48
49 :return bytes: The message digest as bytes.
50
51 .. method:: hexdigest()
52
53 :return str: The message digest as hex.
54