2016-05-06 14:19:10 +00:00
|
|
|
def new(key, msg, digestmod) -> Hmac:
|
|
|
|
###
|
|
|
|
### Creates a HMAC context object.
|
|
|
|
###
|
|
|
|
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)
|
|
|
|
|
2016-05-05 19:41:03 +00:00
|
|
|
def update(self, msg: bytes) -> None:
|
2016-05-06 14:19:10 +00:00
|
|
|
###
|
|
|
|
### 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
|
|
|
|
2016-05-05 19:41:03 +00:00
|
|
|
def digest(self) -> bytes:
|
2016-05-06 14:19:10 +00:00
|
|
|
###
|
|
|
|
### 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
|
|
|
|