hmac.py 4.28 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
class HMAC:
17
    """RFC 2104 HMAC class.  Also complies with RFC 4231.
18

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

    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.
28 29 30
        digestmod: A module supporting PEP 247.  *OR*
                   A hashlib constructor returning a new hash object.
                   Defaults to hashlib.md5.
31 32

        Note: key and msg must be bytes objects.
33
        """
34

35 36
        if not isinstance(key, bytes):
            raise TypeError("expected bytes, but got %r" % type(key).__name__)
37

38
        if digestmod is None:
39 40
            import hashlib
            digestmod = hashlib.md5
41

42
        if callable(digestmod):
43 44
            self.digest_cons = digestmod
        else:
45
            self.digest_cons = lambda d=b'': digestmod.new(d)
46 47 48 49

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

51 52 53 54 55 56 57 58 59 60 61 62 63
        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

64
        if len(key) > blocksize:
65
            key = self.digest_cons(key).digest()
66

67
        key = key + bytes(blocksize - len(key))
68 69
        self.outer.update(key.translate(trans_5C))
        self.inner.update(key.translate(trans_36))
70
        if msg is not None:
71 72 73 74 75
            self.update(msg)

    def update(self, msg):
        """Update this hashing object with the string msg.
        """
76 77
        if not isinstance(msg, bytes):
            raise TypeError("expected bytes, but got %r" % type(msg).__name__)
78 79 80 81 82 83 84
        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.
        """
85 86
        # Call __new__ directly to avoid the expensive __init__.
        other = self.__class__.__new__(self.__class__)
87
        other.digest_cons = self.digest_cons
88
        other.digest_size = self.digest_size
89 90 91
        other.inner = self.inner.copy()
        other.outer = self.outer.copy()
        return other
92

93 94 95 96 97 98 99 100 101
    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

102 103 104 105 106 107 108
    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.
        """
109
        h = self._current()
110 111 112 113 114
        return h.digest()

    def hexdigest(self):
        """Like digest(), but returns a string of hexadecimal digits instead.
        """
115 116
        h = self._current()
        return h.hexdigest()
117 118 119 120 121 122

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
123
    state.
124 125 126 127 128 129

    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)