How Do Your Prevent Cipher Playback? Well, With Associated Data … Meet Poly1305

When we encrypt something, what to stop someone from replaying the cipher at some future time. One way to avoid this is to associate the…

Photo by Folco Masi on Unsplash

How Do Your Prevent Cipher Playback? Well, With Associated Data … Meet Poly1305

When we encrypt something, what to stop someone from replaying the cipher at some future time. One way to avoid this is to associate the cipher with additional data. This might bind the data to a TCP session ID, or even to a given IP address. In this, we can add the additional data to the cipher, and then create an authentication tag. With this tag, we can then check to see if the associated data matches the authentication tag. One of the most used methods for this is Poly1305.

The Poly1305 method is defined in RFC 7539 and can be used to authenticate a message. It takes a message and uses a 256-bit (32-byte) key to produces a 16-byte tag. Overall we should not use the same key after we have signed for a message (as an adversary could fake a take. Often it is used with ChaCha20 (as a stream cipher and to create ChaCha20-Poly1305 for an AEAD (Authenticated Encryption with Associated Data) method.

The following is the code [here]:

import os
import sys
import binascii

from cryptography.hazmat.primitives import poly1305


message = "message"

if (len(sys.argv)>1):
message=str(sys.argv[1])


message=message.encode()
key = os.urandom(32)

c = poly1305.Poly1305(key)

c.update(message)


signature = c.finalize()

print (f"Message: {message.decode()}" )

print (f"Key: {binascii.b2a_hex(key).decode()}")

print (f"\nPoly1305 tag (16 bytes): {binascii.b2a_hex(signature).decode()}")

c = poly1305.Poly1305(key)
c.update(message)

try:
rtn=c.verify(signature)
print ("Signature matches")
except:
print ("Signature does not match")



print ("\n\n--- Generating with alternative method ---")
tag=poly1305.Poly1305.generate_tag(key,message)
print (binascii.b2a_hex(tag).decode())

With Poly1305 we generate a 16-byte tag, and which can be verified against the message. If the associated data fails, the program will create an exception when the signature is checked. A sample run is [here]:

Message: message
Key: a05f355821d29108323b8e76c1c01268c9a24e2c93bbe5ebca7cb4d5e4911261

Poly1305 tag (16 bytes): d5593d53c632d7d164f281d9b8f0ff4f
Signature matches


--- Generating with alternative method ---
d5593d53c632d7d164f281d9b8f0ff4f

Here is the code: