blob: 7bf3c03ea05cb5e4e0cf8c0489f9a7cc77ea8d47 [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 Rossum3f429082007-07-10 13:35:52 +00006trans_5C = bytes((x ^ 0x5C) for x in range(256))
7trans_36 = bytes((x ^ 0x36) for x in range(256))
Tim Petersb64bec32001-09-18 02:26:39 +00008
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +00009# The size of the digests returned by HMAC depends on the underlying
Thomas Wouters902d6eb2007-01-09 23:18:33 +000010# hashing module used. Use digest_size from the instance of HMAC instead.
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000011digest_size = None
12
Tim Peters934d31b2004-03-20 20:11:29 +000013# A unique object passed by HMAC.copy() to the HMAC constructor, in order
14# that the latter return very quickly. HMAC("") in contrast is quite
15# expensive.
16_secret_backdoor_key = []
17
Guido van Rossum8ceef412001-09-11 15:54:00 +000018class HMAC:
19 """RFC2104 HMAC class.
20
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
37 if key is _secret_backdoor_key: # cheap
38 return
39
Guido van Rossum3f429082007-07-10 13:35:52 +000040 if not isinstance(key, bytes):
41 if hasattr(key, "__index__"):
42 raise TypeError("key can't be a number")
43 key = bytes(key)
44
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
Thomas Wouters902d6eb2007-01-09 23:18:33 +000058 blocksize = self.blocksize
Guido van Rossum8ceef412001-09-11 15:54:00 +000059 if len(key) > blocksize:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000060 key = self.digest_cons(key).digest()
Guido van Rossum8ceef412001-09-11 15:54:00 +000061
Guido van Rossum3f429082007-07-10 13:35:52 +000062 key = key + bytes(blocksize - len(key))
Thomas Wouters902d6eb2007-01-09 23:18:33 +000063 self.outer.update(key.translate(trans_5C))
64 self.inner.update(key.translate(trans_36))
Raymond Hettinger094662a2002-06-01 01:29:16 +000065 if msg is not None:
Guido van Rossum8ceef412001-09-11 15:54:00 +000066 self.update(msg)
67
68## def clear(self):
69## raise NotImplementedError, "clear() method not available in HMAC."
70
71 def update(self, msg):
72 """Update this hashing object with the string msg.
73 """
Guido van Rossum3f429082007-07-10 13:35:52 +000074 if not isinstance(msg, bytes):
75 if hasattr(msg, "__index__"):
76 raise TypeError("msg can't be a number")
77 msg = bytes(msg)
Guido van Rossum8ceef412001-09-11 15:54:00 +000078 self.inner.update(msg)
79
80 def copy(self):
81 """Return a separate copy of this hashing object.
82
83 An update to this copy won't affect the original object.
84 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +000085 other = self.__class__(_secret_backdoor_key)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000086 other.digest_cons = self.digest_cons
Tim Peters934d31b2004-03-20 20:11:29 +000087 other.digest_size = self.digest_size
Andrew M. Kuchling1ccdff92001-11-02 21:49:20 +000088 other.inner = self.inner.copy()
89 other.outer = self.outer.copy()
90 return other
Guido van Rossum8ceef412001-09-11 15:54:00 +000091
Thomas Wouters902d6eb2007-01-09 23:18:33 +000092 def _current(self):
93 """Return a hash object for the current state.
94
95 To be used only internally with digest() and hexdigest().
96 """
97 h = self.outer.copy()
98 h.update(self.inner.digest())
99 return h
100
Guido van Rossum8ceef412001-09-11 15:54:00 +0000101 def digest(self):
102 """Return the hash value of this hashing object.
103
104 This returns a string containing 8-bit data. The object is
105 not altered in any way by this function; you can continue
106 updating the object after calling this function.
107 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000108 h = self._current()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000109 return h.digest()
110
111 def hexdigest(self):
112 """Like digest(), but returns a string of hexadecimal digits instead.
113 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000114 h = self._current()
115 return h.hexdigest()
Guido van Rossum8ceef412001-09-11 15:54:00 +0000116
117def new(key, msg = None, digestmod = None):
118 """Create a new hashing object and return it.
119
120 key: The starting key for the hash.
121 msg: if available, will immediately be hashed into the object's starting
Tim Petersb64bec32001-09-18 02:26:39 +0000122 state.
Guido van Rossum8ceef412001-09-11 15:54:00 +0000123
124 You can now feed arbitrary strings into the object using its update()
125 method, and can ask for the hash value at any time by calling its digest()
126 method.
127 """
128 return HMAC(key, msg, digestmod)