| 1 |
Poly1305 |
| 2 |
======== |
| 3 |
|
| 4 |
Poly1305 is a fast Carter-Wegman MAC algorithm created by Daniel J. Bernstein. |
| 5 |
It requires a 32-byte secret key, a 16-byte nonce, and a symmetric cipher. |
| 6 |
The MAC tag is always 16 bytes long. |
| 7 |
|
| 8 |
Originally, Poly1305 was defined_ in combination with :doc:`../cipher/aes`, but it is now most frequently seen used in combination with :doc:`../cipher/chacha20`. |
| 9 |
|
| 10 |
This is an example showing how to generate a MAC tag (note how the nonce is automatically generated at random):: |
| 11 |
|
| 12 |
>>> from Crypto.Hash import Poly1305 |
| 13 |
>>> from Crypto.Cipher import AES |
| 14 |
>>> |
| 15 |
>>> secret = b'Thirtytwo very very secret bytes' |
| 16 |
>>> mac = Poly1305.new(key=secret, cipher=AES) |
| 17 |
>>> mac.update(b'Hello') |
| 18 |
>>> print("Nonce: ", mac.nonce.hex()) |
| 19 |
>>> print("MAC: ", mac.hexdigest()) |
| 20 |
|
| 21 |
This is an example showing how to validate the MAC above:: |
| 22 |
|
| 23 |
>>> from Crypto.Hash import Poly1305 |
| 24 |
>>> from Crypto.Cipher import AES |
| 25 |
>>> from binascii import unhexlify |
| 26 |
>>> |
| 27 |
>>> # We have received a message 'msg' together |
| 28 |
>>> # with its MAC 'mac_tag_hex' and the nonce 'nonce_hex' |
| 29 |
>>> |
| 30 |
>>> secret = b'Thirtytwo very very secret bytes' |
| 31 |
>>> nonce = unhexlify(nonce_hex) |
| 32 |
>>> mac = Poly1305.new(key=secret, nonce=nonce, cipher=AES, data=msg) |
| 33 |
>>> try: |
| 34 |
>>> mac.hexverify(mac_tag_hex) |
| 35 |
>>> print("The message '%s' is authentic" % msg) |
| 36 |
>>> except ValueError: |
| 37 |
>>> print("The message or the key is wrong") |
| 38 |
|
| 39 |
Note that you can get the MAC tag in one line:: |
| 40 |
|
| 41 |
>>> binary_tag = Poly1305.new(key=secret, cipher=AES, data=b'Hello').digest() |
| 42 |
|
| 43 |
Or, for a hexadecimal string:: |
| 44 |
|
| 45 |
>>> hex_tag = Poly1305.new(key=secret, cipher=AES, data=b'Hello').hexdigest() |
| 46 |
|
| 47 |
Equivalently, you can verify a tag with a single line:: |
| 48 |
|
| 49 |
>>> Poly1305.new(key=secret, cipher=AES, data=b'Hello').verify(binary_tag) |
| 50 |
|
| 51 |
or:: |
| 52 |
|
| 53 |
>>> Poly1305.new(key=secret, cipher=AES, data=b'Hello').hexverify(hex_tag) |
| 54 |
|
| 55 |
.. _defined: https://cr.yp.to/mac/poly1305-20050329.pdf |
| 56 |
|
| 57 |
.. automodule:: Crypto.Hash.Poly1305 |
| 58 |
:members: |