blob: 0f59fd4847afe2d54ee19a71b0f0fb01e6e433eb [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# A unique object passed by HMAC.copy() to the HMAC constructor, in order
16# that the latter return very quickly. HMAC("") in contrast is quite
17# expensive.
18_secret_backdoor_key = []
19
Guido van Rossum8ceef412001-09-11 15:54:00 +000020class HMAC:
Guido van Rossuma19f80c2007-11-06 20:51:31 +000021 """RFC 2104 HMAC class. Also complies with RFC 4231.
Guido van Rossum8ceef412001-09-11 15:54:00 +000022
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000023 This supports the API for Cryptographic Hash Functions (PEP 247).
Tim Petersb64bec32001-09-18 02:26:39 +000024 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000025 blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
Guido van Rossum8ceef412001-09-11 15:54:00 +000026
27 def __init__(self, key, msg = None, digestmod = None):
28 """Create a new HMAC object.
29
30 key: key for the keyed hash object.
31 msg: Initial input for the hash, if provided.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000032 digestmod: A module supporting PEP 247. *OR*
33 A hashlib constructor returning a new hash object.
34 Defaults to hashlib.md5.
Guido van Rossum3f429082007-07-10 13:35:52 +000035
36 Note: key and msg must be bytes objects.
Guido van Rossum8ceef412001-09-11 15:54:00 +000037 """
Tim Peters934d31b2004-03-20 20:11:29 +000038
39 if key is _secret_backdoor_key: # cheap
40 return
41
Alexandre Vassalottia351f772008-03-03 02:59:49 +000042 if not isinstance(key, bytes):
43 raise TypeError("expected bytes, but got %r" % type(key).__name__)
Guido van Rossum3f429082007-07-10 13:35:52 +000044
Raymond Hettinger7fdfc2d2002-05-31 17:49:10 +000045 if digestmod is None:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000046 import hashlib
47 digestmod = hashlib.md5
Guido van Rossum8ceef412001-09-11 15:54:00 +000048
Guido van Rossumd59da4b2007-05-22 18:11:13 +000049 if hasattr(digestmod, '__call__'):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000050 self.digest_cons = digestmod
51 else:
Guido van Rossum3f429082007-07-10 13:35:52 +000052 self.digest_cons = lambda d=b'': digestmod.new(d)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000053
54 self.outer = self.digest_cons()
55 self.inner = self.digest_cons()
56 self.digest_size = self.inner.digest_size
Tim Peters88768482001-11-13 21:51:26 +000057
Guido van Rossuma19f80c2007-11-06 20:51:31 +000058 if hasattr(self.inner, 'block_size'):
59 blocksize = self.inner.block_size
60 if blocksize < 16:
61 # Very low blocksize, most likely a legacy value like
62 # Lib/sha.py and Lib/md5.py have.
63 _warnings.warn('block_size of %d seems too small; using our '
64 'default of %d.' % (blocksize, self.blocksize),
65 RuntimeWarning, 2)
66 blocksize = self.blocksize
67 else:
68 _warnings.warn('No block_size attribute on given digest object; '
69 'Assuming %d.' % (self.blocksize),
70 RuntimeWarning, 2)
71 blocksize = self.blocksize
72
Guido van Rossum8ceef412001-09-11 15:54:00 +000073 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000074 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000075
Guido van Rossum3f429082007-07-10 13:35:52 +000076 key = key + bytes(blocksize - len(key))
Thomas Wouters902d6eb2007-01-09 23:18:33 +000077 self.outer.update(key.translate(trans_5C))
78 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000079 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000080 self.update(msg)
81
82## def clear(self):
83## raise NotImplementedError, "clear() method not available in HMAC."
84
85 def update(self, msg):
86 """Update this hashing object with the string msg.
87 """
Alexandre Vassalottia351f772008-03-03 02:59:49 +000088 if not isinstance(msg, bytes):
89 raise TypeError("expected bytes, but got %r" % type(msg).__name__)
Guido van Rossum8ceef412001-09-11 15:54:00 +000090 self.inner.update(msg)
91
92 def copy(self):
93 """Return a separate copy of this hashing object.
94
95 An update to this copy won't affect the original object.
96 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000097 other = self.__class__(_secret_backdoor_key)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000098 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +000099 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +0000100 other.inner = self.inner.copy()
101 other.outer = self.outer.copy()
102 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +0000103
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000104 def _current(self):
105 """Return a hash object for the current state.
106
107 To be used only internally with digest() and hexdigest().
108 """
109 h = self.outer.copy()
110 h.update(self.inner.digest())
111 return h
112
Guido van Rossum8ceef412001-09-11 15:54:00 +0000113 def digest(self):
114 """Return the hash value of this hashing object.
115
116 This returns a string containing 8-bit data. The object is
117 not altered in any way by this function; you can continue
118 updating the object after calling this function.
119 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000120 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000121 return h.digest()
122
123 def hexdigest(self):
124 """Like digest(), but returns a string of hexadecimal digits instead.
125 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000126 h = self._current()
127 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000128
129def new(key, msg = None, digestmod = None):
130 """Create a new hashing object and return it.
131
132 key: The starting key for the hash.
133 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000134 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000135
136 You can now feed arbitrary strings into the object using its update()
137 method, and can ask for the hash value at any time by calling its digest()
138 method.
139 """
140 return HMAC(key, msg, digestmod)