1 """HMAC (Keyed-Hashing for Message Authentication) Python module. 2 3 Implements the HMAC algorithm as described by RFC 2104. 4 """ 5 6 import warnings as _warnings 7 from _operator import _compare_digest as compare_digest 8 import hashlib as _hashlib 9 10 trans_5C = bytes((x ^ 0x5C) for x in range(256)) 11 trans_36 = bytes((x ^ 0x36) for x in range(256)) 12 13 # The size of the digests returned by HMAC depends on the underlying 14 # hashing module used. Use digest_size from the instance of HMAC instead. 15 digest_size = None 16 17 18 19 class HMAC: 20 """RFC 2104 HMAC class. Also complies with RFC 4231. 21 22 This supports the API for Cryptographic Hash Functions (PEP 247). 23 """ 24 blocksize = 64 # 512-bit HMAC; can be changed in subclasses. 25 26 def __init__(self, key, msg = None, digestmod = None): 27 """Create a new HMAC object. 28 29 key: key for the keyed hash object. 30 msg: Initial input for the hash, if provided. 31 digestmod: A module supporting PEP 247. *OR* 32 A hashlib constructor returning a new hash object. *OR* 33 A hash name suitable for hashlib.new(). 34 Defaults to hashlib.md5. 35 Implicit default to hashlib.md5 is deprecated and will be 36 removed in Python 3.6. 37 38 Note: key and msg must be a bytes or bytearray objects. 39 """ 40 41 if not isinstance(key, (bytes, bytearray)): 42 raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) 43 44 if digestmod is None: 45 _warnings.warn("HMAC() without an explicit digestmod argument " 46 "is deprecated.", PendingDeprecationWarning, 2) 47 digestmod = _hashlib.md5 48 49 if callable(digestmod): 50 self.digest_cons = digestmod 51 elif isinstance(digestmod, str): 52 self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d) 53 else: 54 self.digest_cons = lambda d=b'': digestmod.new(d) 55 56 self.outer = self.digest_cons() 57 self.inner = self.digest_cons() 58 self.digest_size = self.inner.digest_size 59 60 if hasattr(self.inner, 'block_size'): 61 blocksize = self.inner.block_size 62 if blocksize < 16: 63 _warnings.warn('block_size of %d seems too small; using our ' 64 'default of %d.' % (blocksize, self.blocksize), 65 RuntimeWarning, 2) 66 blocksize = self.blocksize 67 else: 68 _warnings.warn('No block_size attribute on given digest object; ' 69 'Assuming %d.' % (self.blocksize), 70 RuntimeWarning, 2) 71 blocksize = self.blocksize 72 73 # self.blocksize is the default blocksize. self.block_size is 74 # effective block size as well as the public API attribute. 75 self.block_size = blocksize 76 77 if len(key) > blocksize: 78 key = self.digest_cons(key).digest() 79 80 key = key.ljust(blocksize, b'