hmac.py 4.94 KB
Newer Older
1 2 3 4 5
"""HMAC (Keyed-Hashing for Message Authentication) Python module.

Implements the HMAC algorithm as described by RFC 2104.
"""

6
import warnings as _warnings
7
from _operator import _compare_digest as compare_digest
8
import hashlib as _hashlib
9

10 11
trans_5C = bytes((x ^ 0x5C) for x in range(256))
trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Peters's avatar
Tim Peters committed
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 16
digest_size = None

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).
Tim Peters's avatar
Tim Peters committed
23
    """
24
    blocksize = 64  # 512-bit HMAC; can be changed in subclasses.
25 26 27 28 29 30

    def __init__(self, key, msg = None, digestmod = None):
        """Create a new HMAC object.

        key:       key for the keyed hash object.
        msg:       Initial input for the hash, if provided.
31
        digestmod: A module supporting PEP 247.  *OR*
32 33
                   A hashlib constructor returning a new hash object. *OR*
                   A hash name suitable for hashlib.new().
34
                   Defaults to hashlib.md5.
35 36
                   Implicit default to hashlib.md5 is deprecated and will be
                   removed in Python 3.6.
37

38
        Note: key and msg must be a bytes or bytearray objects.
39
        """
40

41 42
        if not isinstance(key, (bytes, bytearray)):
            raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
43

44
        if digestmod is None:
45 46 47
            _warnings.warn("HMAC() without an explicit digestmod argument "
                           "is deprecated.", PendingDeprecationWarning, 2)
            digestmod = _hashlib.md5
48

49
        if callable(digestmod):
50
            self.digest_cons = digestmod
51 52
        elif isinstance(digestmod, str):
            self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
53
        else:
54
            self.digest_cons = lambda d=b'': digestmod.new(d)
55 56 57 58

        self.outer = self.digest_cons()
        self.inner = self.digest_cons()
        self.digest_size = self.inner.digest_size
Tim Peters's avatar
Tim Peters committed
59

60 61 62 63 64 65 66 67 68 69 70 71 72
        if hasattr(self.inner, 'block_size'):
            blocksize = self.inner.block_size
            if blocksize < 16:
                _warnings.warn('block_size of %d seems too small; using our '
                               'default of %d.' % (blocksize, self.blocksize),
                               RuntimeWarning, 2)
                blocksize = self.blocksize
        else:
            _warnings.warn('No block_size attribute on given digest object; '
                           'Assuming %d.' % (self.blocksize),
                           RuntimeWarning, 2)
            blocksize = self.blocksize

73 74 75 76
        # self.blocksize is the default blocksize. self.block_size is
        # effective block size as well as the public API attribute.
        self.block_size = blocksize

77
        if len(key) > blocksize:
78
            key = self.digest_cons(key).digest()
79

80
        key = key + bytes(blocksize - len(key))
81 82
        self.outer.update(key.translate(trans_5C))
        self.inner.update(key.translate(trans_36))
83
        if msg is not None:
84 85
            self.update(msg)

86 87 88 89
    @property
    def name(self):
        return "hmac-" + self.inner.name

90 91 92 93 94 95 96 97 98 99
    def update(self, msg):
        """Update this hashing object with the string msg.
        """
        self.inner.update(msg)

    def copy(self):
        """Return a separate copy of this hashing object.

        An update to this copy won't affect the original object.
        """
100 101
        # Call __new__ directly to avoid the expensive __init__.
        other = self.__class__.__new__(self.__class__)
102
        other.digest_cons = self.digest_cons
103
        other.digest_size = self.digest_size
104 105 106
        other.inner = self.inner.copy()
        other.outer = self.outer.copy()
        return other
107

108 109 110 111 112 113 114 115 116
    def _current(self):
        """Return a hash object for the current state.

        To be used only internally with digest() and hexdigest().
        """
        h = self.outer.copy()
        h.update(self.inner.digest())
        return h

117 118 119 120 121 122 123
    def digest(self):
        """Return the hash value of this hashing object.

        This returns a string containing 8-bit data.  The object is
        not altered in any way by this function; you can continue
        updating the object after calling this function.
        """
124
        h = self._current()
125 126 127 128 129
        return h.digest()

    def hexdigest(self):
        """Like digest(), but returns a string of hexadecimal digits instead.
        """
130 131
        h = self._current()
        return h.hexdigest()
132 133 134 135 136 137

def new(key, msg = None, digestmod = None):
    """Create a new hashing object and return it.

    key: The starting key for the hash.
    msg: if available, will immediately be hashed into the object's starting
Tim Peters's avatar
Tim Peters committed
138
    state.
139 140 141 142 143 144

    You can now feed arbitrary strings into the object using its update()
    method, and can ask for the hash value at any time by calling its digest()
    method.
    """
    return HMAC(key, msg, digestmod)