blob: 13ffdbe14b231b05c83805fc083507c8f9a95da1 [file] [log] [blame]
Guido van Rossum8ceef412001-09-11 15:54:00 +00001"""HMAC (Keyed-Hashing for Message Authentication) Python module.
2
3Implements the HMAC algorithm as described by RFC 2104.
4"""
5
Guido van Rossuma19f80c2007-11-06 20:51:31 +00006import warnings as _warnings
7
Guido van Rossum3f429082007-07-10 13:35:52 +00008trans_5C = bytes((x ^ 0x5C) for x in range(256))
9trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +000010
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000011# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000012# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000013digest_size = None
14
Tim Peters934d31b2004-03-20 20:11:29 +000015
Charles-François Natali7feb9f42012-05-13 19:53:07 +020016def secure_compare(a, b):
17 """Returns the equivalent of 'a == b', but using a time-independent
18 comparison method to prevent timing attacks."""
19 if not ((isinstance(a, str) and isinstance(b, str)) or
20 (isinstance(a, bytes) and isinstance(b, bytes))):
21 raise TypeError("inputs must be strings or bytes")
22
23 if len(a) != len(b):
24 return False
25
26 result = 0
27 if isinstance(a, bytes):
28 for x, y in zip(a, b):
29 result |= x ^ y
30 else:
31 for x, y in zip(a, b):
32 result |= ord(x) ^ ord(y)
33
34 return result == 0
35
36
Guido van Rossum8ceef412001-09-11 15:54:00 +000037class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000038 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000039
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000040 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000041 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000042 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000043
44 def __init__(self, key, msg = None, digestmod = None):
45 """Create a new HMAC object.
46
47 key: key for the keyed hash object.
48 msg: Initial input for the hash, if provided.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000049 digestmod: A module supporting PEP 247. *OR*
50 A hashlib constructor returning a new hash object.
51 Defaults to hashlib.md5.
Guido van Rossum3f429082007-07-10 13:35:52 +000052
53 Note: key and msg must be bytes objects.
Guido van Rossum8ceef412001-09-11 15:54:00 +000054 """
Tim Peters934d31b2004-03-20 20:11:29 +000055
Alexandre Vassalottia351f772008-03-03 02:59:49 +000056 if not isinstance(key, bytes):
57 raise TypeError("expected bytes, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000058
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000059 if digestmod is None:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000060 import hashlib
61 digestmod = hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000062
Florent Xicluna5d1155c2011-10-28 14:45:05 +020063 if callable(digestmod):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000064 self.digest_cons = digestmod
65 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000066 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000067
68 self.outer = self.digest_cons()
69 self.inner = self.digest_cons()
70 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000071
Guido van Rossuma19f80c2007-11-06 20:51:31 +000072 if hasattr(self.inner, 'block_size'):
73 blocksize = self.inner.block_size
74 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000075 _warnings.warn('block_size of %d seems too small; using our '
76 'default of %d.' % (blocksize, self.blocksize),
77 RuntimeWarning, 2)
78 blocksize = self.blocksize
79 else:
80 _warnings.warn('No block_size attribute on given digest object; '
81 'Assuming %d.' % (self.blocksize),
82 RuntimeWarning, 2)
83 blocksize = self.blocksize
84
Guido van Rossum8ceef412001-09-11 15:54:00 +000085 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000086 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000087
Guido van Rossum3f429082007-07-10 13:35:52 +000088 key = key + bytes(blocksize - len(key))
Thomas Wouters902d6eb2007-01-09 23:18:33 +000089 self.outer.update(key.translate(trans_5C))
90 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000091 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000092 self.update(msg)
93
Guido van Rossum8ceef412001-09-11 15:54:00 +000094 def update(self, msg):
95 """Update this hashing object with the string msg.
96 """
Alexandre Vassalottia351f772008-03-03 02:59:49 +000097 if not isinstance(msg, bytes):
98 raise TypeError("expected bytes, but got %r" % type(msg).__name__)
Guido van Rossum8ceef412001-09-11 15:54:00 +000099 self.inner.update(msg)
100
101 def copy(self):
102 """Return a separate copy of this hashing object.
103
104 An update to this copy won't affect the original object.
105 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +0000106 # Call __new__ directly to avoid the expensive __init__.
107 other = self.__class__.__new__(self.__class__)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000108 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +0000109 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000110 other.inner = self.inner.copy()
111 other.outer = self.outer.copy()
112 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000113
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000114 def _current(self):
115 """Return a hash object for the current state.
116
117 To be used only internally with digest() and hexdigest().
118 """
119 h = self.outer.copy()
120 h.update(self.inner.digest())
121 return h
122
Guido van Rossum8ceef412001-09-11 15:54:00 +0000123 def digest(self):
124 """Return the hash value of this hashing object.
125
126 This returns a string containing 8-bit data. The object is
127 not altered in any way by this function; you can continue
128 updating the object after calling this function.
129 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000130 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000131 return h.digest()
132
133 def hexdigest(self):
134 """Like digest(), but returns a string of hexadecimal digits instead.
135 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000136 h = self._current()
137 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000138
139def new(key, msg = None, digestmod = None):
140 """Create a new hashing object and return it.
141
142 key: The starting key for the hash.
143 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000144 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000145
146 You can now feed arbitrary strings into the object using its update()
147 method, and can ask for the hash value at any time by calling its digest()
148 method.
149 """
150 return HMAC(key, msg, digestmod)