blob: 4297a7171abe6ece187d95cbb2deaee26fab9ee5 [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
Christian Heimes6cea6552012-06-24 13:48:32 +02007from operator import _compare_digest as compare_digest
Guido van Rossuma19f80c2007-11-06 20:51:31 +00008
Guido van Rossum3f429082007-07-10 13:35:52 +00009trans_5C = bytes((x ^ 0x5C) for x in range(256))
10trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +000011
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000012# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000013# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000014digest_size = None
15
Tim Peters934d31b2004-03-20 20:11:29 +000016
Charles-François Natali7feb9f42012-05-13 19:53:07 +020017
Guido van Rossum8ceef412001-09-11 15:54:00 +000018class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000019 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000020
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000021 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000022 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000023 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000024
25 def __init__(self, key, msg = None, digestmod = None):
26 """Create a new HMAC object.
27
28 key: key for the keyed hash object.
29 msg: Initial input for the hash, if provided.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000030 digestmod: A module supporting PEP 247. *OR*
31 A hashlib constructor returning a new hash object.
32 Defaults to hashlib.md5.
Guido van Rossum3f429082007-07-10 13:35:52 +000033
34 Note: key and msg must be bytes objects.
Guido van Rossum8ceef412001-09-11 15:54:00 +000035 """
Tim Peters934d31b2004-03-20 20:11:29 +000036
Alexandre Vassalottia351f772008-03-03 02:59:49 +000037 if not isinstance(key, bytes):
Antoine Pitrou24ef3e92012-06-30 17:27:56 +020038 raise TypeError("key: expected bytes, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000039
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000040 if digestmod is None:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000041 import hashlib
42 digestmod = hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000043
Florent Xicluna5d1155c2011-10-28 14:45:05 +020044 if callable(digestmod):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000045 self.digest_cons = digestmod
46 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000047 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000048
49 self.outer = self.digest_cons()
50 self.inner = self.digest_cons()
51 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000052
Guido van Rossuma19f80c2007-11-06 20:51:31 +000053 if hasattr(self.inner, 'block_size'):
54 blocksize = self.inner.block_size
55 if blocksize < 16:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000056 _warnings.warn('block_size of %d seems too small; using our '
57 'default of %d.' % (blocksize, self.blocksize),
58 RuntimeWarning, 2)
59 blocksize = self.blocksize
60 else:
61 _warnings.warn('No block_size attribute on given digest object; '
62 'Assuming %d.' % (self.blocksize),
63 RuntimeWarning, 2)
64 blocksize = self.blocksize
65
Guido van Rossum8ceef412001-09-11 15:54:00 +000066 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000067 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000068
Guido van Rossum3f429082007-07-10 13:35:52 +000069 key = key + bytes(blocksize - len(key))
Thomas Wouters902d6eb2007-01-09 23:18:33 +000070 self.outer.update(key.translate(trans_5C))
71 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000072 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000073 self.update(msg)
74
Guido van Rossum8ceef412001-09-11 15:54:00 +000075 def update(self, msg):
76 """Update this hashing object with the string msg.
77 """
Alexandre Vassalottia351f772008-03-03 02:59:49 +000078 if not isinstance(msg, bytes):
79 raise TypeError("expected bytes, but got %r" % type(msg).__name__)
Guido van Rossum8ceef412001-09-11 15:54:00 +000080 self.inner.update(msg)
81
82 def copy(self):
83 """Return a separate copy of this hashing object.
84
85 An update to this copy won't affect the original object.
86 """
Benjamin Peterson0cc74442010-08-21 02:45:15 +000087 # Call __new__ directly to avoid the expensive __init__.
88 other = self.__class__.__new__(self.__class__)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000089 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +000090 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000091 other.inner = self.inner.copy()
92 other.outer = self.outer.copy()
93 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +000094
Thomas Wouters902d6eb2007-01-09 23:18:33 +000095 def _current(self):
96 """Return a hash object for the current state.
97
98 To be used only internally with digest() and hexdigest().
99 """
100 h = self.outer.copy()
101 h.update(self.inner.digest())
102 return h
103
Guido van Rossum8ceef412001-09-11 15:54:00 +0000104 def digest(self):
105 """Return the hash value of this hashing object.
106
107 This returns a string containing 8-bit data. The object is
108 not altered in any way by this function; you can continue
109 updating the object after calling this function.
110 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000111 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000112 return h.digest()
113
114 def hexdigest(self):
115 """Like digest(), but returns a string of hexadecimal digits instead.
116 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000117 h = self._current()
118 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000119
120def new(key, msg = None, digestmod = None):
121 """Create a new hashing object and return it.
122
123 key: The starting key for the hash.
124 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000125 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000126
127 You can now feed arbitrary strings into the object using its update()
128 method, and can ask for the hash value at any time by calling its digest()
129 method.
130 """
131 return HMAC(key, msg, digestmod)