hmac.py 4.68 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 7
import warnings as _warnings

8 9
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
10

11
# The size of the digests returned by HMAC depends on the underlying
12
# hashing module used.  Use digest_size from the instance of HMAC instead.
13 14
digest_size = None

15 16 17 18 19
# A unique object passed by HMAC.copy() to the HMAC constructor, in order
# that the latter return very quickly.  HMAC("") in contrast is quite
# expensive.
_secret_backdoor_key = []

20
class HMAC:
21
    """RFC 2104 HMAC class.  Also complies with RFC 4231.
22

23
    This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Peters's avatar
Tim Peters committed
24
    """
25
    blocksize = 64  # 512-bit HMAC; can be changed in subclasses.
26 27 28 29 30 31

    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.
32 33 34
        digestmod: A module supporting PEP 247.  *OR*
                   A hashlib constructor returning a new hash object.
                   Defaults to hashlib.md5.
35 36

        Note: key and msg must be bytes objects.
37
        """
38 39 40 41

        if key is _secret_backdoor_key: # cheap
            return

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

45
        if digestmod is None:
46 47
            import hashlib
            digestmod = hashlib.md5
48

49
        if hasattr(digestmod, '__call__'):
50 51
            self.digest_cons = digestmod
        else:
52
            self.digest_cons = lambda d=b'': digestmod.new(d)
53 54 55 56

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

58 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:
                # Very low blocksize, most likely a legacy value like
                # Lib/sha.py and Lib/md5.py have.
                _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
        if len(key) > blocksize:
74
            key = self.digest_cons(key).digest()
75

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

##    def clear(self):
##        raise NotImplementedError, "clear() method not available in HMAC."

    def update(self, msg):
        """Update this hashing object with the string msg.
        """
88 89
        if not isinstance(msg, bytes):
            raise TypeError("expected bytes, but got %r" % type(msg).__name__)
90 91 92 93 94 95 96
        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.
        """
97
        other = self.__class__(_secret_backdoor_key)
98
        other.digest_cons = self.digest_cons
99
        other.digest_size = self.digest_size
100 101 102
        other.inner = self.inner.copy()
        other.outer = self.outer.copy()
        return other
103

104 105 106 107 108 109 110 111 112
    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

113 114 115 116 117 118 119
    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.
        """
120
        h = self._current()
121 122 123 124 125
        return h.digest()

    def hexdigest(self):
        """Like digest(), but returns a string of hexadecimal digits instead.
        """
126 127
        h = self._current()
        return h.hexdigest()
128 129 130 131 132 133

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
134
    state.
135 136 137 138 139 140

    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)