from hashlib import sha256
from Crypto.Util.number import long_to_bytes
from Crypto.Util.Padding import pad
def __init__(self, k1 = os.urandom(16), k2 = os.urandom(16)):
nonce_block = long_to_bytes(self.ctr, 2)
prev_block = nonce_block + m[:30]
for i in range(nb_blocks - 1):
nonce_block = long_to_bytes(self.ctr, 2)
next_block = nonce_block + m[30*(i+1):30*(i+2)]
big_block = prev_block + next_block
digest = hmac.new(self.k1, big_block, sha256).digest()
tag_hash = bytearray([x ^ y for (x,y) in zip(tag_hash, digest)])
tag_nonce = tag_nonce + nonce_block
tag_hash = hmac.new(self.k2, tag_hash, sha256).digest()
return tag_hash, tag_nonce
def verify(self, input, tag):
tag_hash, tag_nonce = tag
nb_blocks_m = len(m) // 30
nb_blocks_nonce = len(tag_nonce) // 2
if nb_blocks_nonce != nb_blocks_m:
if len(tag_nonce) % 2 != 0 or len(tag_hash) % 32 != 0:
tag_hash_ = bytearray(32)
prev_block = tag_nonce[:2] + m[:30]
for i in range(nb_blocks_m - 1):
next_block = tag_nonce[2*(i+1):2*(i+2)] + m[30*(i+1):30*(i+2)]
big_block = prev_block + next_block
digest = hmac.new(self.k1, big_block, sha256).digest()
tag_hash_ = bytearray([x ^ y for (x,y) in zip(tag_hash_, digest)])
tag_hash_recomputed = hmac.new(self.k2, tag_hash_, sha256).digest()
return (tag_hash == tag_hash_recomputed)
print("|-> t tag a message")
print("|-> v verify a couple (message, tag)")
if __name__ == "__main__":
if len(cmd) == 0 or cmd not in ['t', 'v', 'q']:
print("Input the message:")
message = str.encode(input(">>> "))
print("Error: the message must not be empty.")
tag = macaron.tag(message)
print("Tag hash: {}".format(tag[0].hex()))
print("Tag nonce: {}".format(tag[1].hex()))
print("Input the message to verify:")
message = str.encode(input(">>> "))
print("Error: the message must not be empty.")
print("Input the associated tag hash:")
tag_hash = bytearray.fromhex(input(">>> "))
print("Input the associated tag nonce:")
tag_nonce = bytearray.fromhex(input(">>> "))
check = macaron.verify(message, (tag_hash, tag_nonce))
print("Congrats!! Here is the flag: {}".format(flag))
print("Tag valid, but this message is not new.")
print("Invalid tag. Try again")
print("Error: check your input.")