1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2025-01-24 14:20:57 +00:00
trezor-firmware/src/trezor/crypto/hmac.py

36 lines
1.0 KiB
Python
Raw Normal View History

2016-05-06 14:19:10 +00:00
def new(key, msg, digestmod) -> Hmac:
'''
Creates a HMAC context object.
'''
2016-05-06 14:19:10 +00:00
return Hmac(key, msg, digestmod)
2016-04-14 16:40:13 +00:00
class Hmac:
2016-04-14 18:08:27 +00:00
def __init__(self, key, msg, digestmod):
self.__digestmod = digestmod
self.__inner = digestmod()
self.digest_size = self.__inner.digest_size
self.block_size = self.__inner.block_size
2016-04-14 16:40:13 +00:00
if len(key) > self.block_size:
2016-04-14 18:08:27 +00:00
key = digestmod(key).digest()
self.__key = key + bytes(self.block_size - len(key))
self.__inner.update(bytes((x ^ 0x36) for x in self.__key))
2016-04-14 16:40:13 +00:00
if msg is not None:
self.update(msg)
def update(self, msg: bytes) -> None:
'''
Update the context with data.
'''
2016-04-14 18:08:27 +00:00
self.__inner.update(msg)
2016-04-14 16:40:13 +00:00
def digest(self) -> bytes:
'''
Returns the digest of processed data.
'''
2016-04-14 18:08:27 +00:00
outer = self.__digestmod()
outer.update(bytes((x ^ 0x5C) for x in self.__key))
outer.update(self.__inner.digest())
2016-04-14 16:40:13 +00:00
return outer.digest()
2016-05-06 14:19:10 +00:00