| 1 |
HMAC |
| 2 |
==== |
| 3 |
|
| 4 |
HMAC (Hash-based Message Authentication Code) is a MAC defined |
| 5 |
in RFC2104_ and FIPS-198_ and constructed using a cryptographic |
| 6 |
hash algorithm. |
| 7 |
|
| 8 |
It is usually named *HMAC-X*, where *X* is the hash algorithm; for |
| 9 |
instance *HMAC-SHA1* or *HMAC-SHA256*. |
| 10 |
|
| 11 |
The strength of an HMAC depends on: |
| 12 |
|
| 13 |
* the strength of the hash algorithm |
| 14 |
* the entropy of the secret key |
| 15 |
|
| 16 |
This is an example showing how to generate a MAC (with *HMAC-SHA256*):: |
| 17 |
|
| 18 |
>>> from Crypto.Hash import HMAC, SHA256 |
| 19 |
>>> |
| 20 |
>>> secret = b'Swordfish' |
| 21 |
>>> h = HMAC.new(secret, digestmod=SHA256) |
| 22 |
>>> h.update(b'Hello') |
| 23 |
>>> print(h.hexdigest()) |
| 24 |
|
| 25 |
This is an example showing how to validate the MAC:: |
| 26 |
|
| 27 |
>>> from Crypto.Hash import HMAC, SHA256 |
| 28 |
>>> |
| 29 |
>>> # We have received a message 'msg' together |
| 30 |
>>> # with its MAC 'mac' |
| 31 |
>>> |
| 32 |
>>> secret = b'Swordfish' |
| 33 |
>>> h = HMAC.new(secret, digestmod=SHA256) |
| 34 |
>>> h.update(msg) |
| 35 |
>>> try: |
| 36 |
>>> h.hexverify(mac) |
| 37 |
>>> print("The message '%s' is authentic" % msg) |
| 38 |
>>> except ValueError: |
| 39 |
>>> print("The message or the key is wrong") |
| 40 |
|
| 41 |
.. _RFC2104: http://www.ietf.org/rfc/rfc2104.txt |
| 42 |
.. _FIPS-198: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.198-1.pdf |
| 43 |
|
| 44 |
.. automodule:: Crypto.Hash.HMAC |
| 45 |
:members: |