1"""HMAC (Keyed-Hashing for Message Authentication) module.
2
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
6import warnings as _warnings
7from _operator import _compare_digest as compare_digest
8try:
9    import _hashlib as _hashopenssl
10except ImportError:
11    _hashopenssl = None
12    _openssl_md_meths = None
13else:
14    _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
15import hashlib as _hashlib
16
17trans_5C = bytes((x ^ 0x5C) for x in range(256))
18trans_36 = bytes((x ^ 0x36) for x in range(256))
19
20# The size of the digests returned by HMAC depends on the underlying
21# hashing module used.  Use digest_size from the instance of HMAC instead.
22digest_size = None
23
24
25
26class HMAC:
27    """RFC 2104 HMAC class.  Also complies with RFC 4231.
28
29    This supports the API for Cryptographic Hash Functions (PEP 247).
30    """
31    blocksize = 64  # 512-bit HMAC; can be changed in subclasses.
32
33    def __init__(self, key, msg=None, digestmod=''):
34        """Create a new HMAC object.
35
36        key: bytes or buffer, key for the keyed hash object.
37        msg: bytes or buffer, Initial input for the hash or None.
38        digestmod: A hash name suitable for hashlib.new(). *OR*
39                   A hashlib constructor returning a new hash object. *OR*
40                   A module supporting PEP 247.
41
42                   Required as of 3.8, despite its position after the optional
43                   msg argument.  Passing it as a keyword argument is
44                   recommended, though not required for legacy API reasons.
45        """
46
47        if not isinstance(key, (bytes, bytearray)):
48            raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
49
50        if not digestmod:
51            raise TypeError("Missing required parameter 'digestmod'.")
52
53        if callable(digestmod):
54            self.digest_cons = digestmod
55        elif isinstance(digestmod, str):
56            self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
57        else:
58            self.digest_cons = lambda d=b'': digestmod.new(d)
59
60        self.outer = self.digest_cons()
61        self.inner = self.digest_cons()
62        self.digest_size = self.inner.digest_size
63
64        if hasattr(self.inner, 'block_size'):
65            blocksize = self.inner.block_size
66            if blocksize < 16:
67                _warnings.warn('block_size of %d seems too small; using our '
68                               'default of %d.' % (blocksize, self.blocksize),
69                               RuntimeWarning, 2)
70                blocksize = self.blocksize
71        else:
72            _warnings.warn('No block_size attribute on given digest object; '
73                           'Assuming %d.' % (self.blocksize),
74                           RuntimeWarning, 2)
75            blocksize = self.blocksize
76
77        # self.blocksize is the default blocksize. self.block_size is
78        # effective block size as well as the public API attribute.
79        self.block_size = blocksize
80
81        if len(key) > blocksize:
82            key = self.digest_cons(key).digest()
83
84        key = key.ljust(blocksize, b'\0')
85        self.outer.update(key.translate(trans_5C))
86        self.inner.update(key.translate(trans_36))
87        if msg is not None:
88            self.update(msg)
89
90    @property
91    def name(self):
92        return "hmac-" + self.inner.name
93
94    def update(self, msg):
95        """Feed data from msg into this hashing object."""
96        self.inner.update(msg)
97
98    def copy(self):
99        """Return a separate copy of this hashing object.
100
101        An update to this copy won't affect the original object.
102        """
103        # Call __new__ directly to avoid the expensive __init__.
104        other = self.__class__.__new__(self.__class__)
105        other.digest_cons = self.digest_cons
106        other.digest_size = self.digest_size
107        other.inner = self.inner.copy()
108        other.outer = self.outer.copy()
109        return other
110
111    def _current(self):
112        """Return a hash object for the current state.
113
114        To be used only internally with digest() and hexdigest().
115        """
116        h = self.outer.copy()
117        h.update(self.inner.digest())
118        return h
119
120    def digest(self):
121        """Return the hash value of this hashing object.
122
123        This returns the hmac value as bytes.  The object is
124        not altered in any way by this function; you can continue
125        updating the object after calling this function.
126        """
127        h = self._current()
128        return h.digest()
129
130    def hexdigest(self):
131        """Like digest(), but returns a string of hexadecimal digits instead.
132        """
133        h = self._current()
134        return h.hexdigest()
135
136def new(key, msg=None, digestmod=''):
137    """Create a new hashing object and return it.
138
139    key: bytes or buffer, The starting key for the hash.
140    msg: bytes or buffer, Initial input for the hash, or None.
141    digestmod: A hash name suitable for hashlib.new(). *OR*
142               A hashlib constructor returning a new hash object. *OR*
143               A module supporting PEP 247.
144
145               Required as of 3.8, despite its position after the optional
146               msg argument.  Passing it as a keyword argument is
147               recommended, though not required for legacy API reasons.
148
149    You can now feed arbitrary bytes into the object using its update()
150    method, and can ask for the hash value at any time by calling its digest()
151    or hexdigest() methods.
152    """
153    return HMAC(key, msg, digestmod)
154
155
156def digest(key, msg, digest):
157    """Fast inline implementation of HMAC.
158
159    key: bytes or buffer, The key for the keyed hash object.
160    msg: bytes or buffer, Input message.
161    digest: A hash name suitable for hashlib.new() for best performance. *OR*
162            A hashlib constructor returning a new hash object. *OR*
163            A module supporting PEP 247.
164    """
165    if (_hashopenssl is not None and
166            isinstance(digest, str) and digest in _openssl_md_meths):
167        return _hashopenssl.hmac_digest(key, msg, digest)
168
169    if callable(digest):
170        digest_cons = digest
171    elif isinstance(digest, str):
172        digest_cons = lambda d=b'': _hashlib.new(digest, d)
173    else:
174        digest_cons = lambda d=b'': digest.new(d)
175
176    inner = digest_cons()
177    outer = digest_cons()
178    blocksize = getattr(inner, 'block_size', 64)
179    if len(key) > blocksize:
180        key = digest_cons(key).digest()
181    key = key + b'\x00' * (blocksize - len(key))
182    inner.update(key.translate(trans_36))
183    outer.update(key.translate(trans_5C))
184    inner.update(msg)
185    outer.update(inner.digest())
186    return outer.digest()
187