|
1 | | -"""HMAC (Keyed-Hashing for Message Authentication) Python module. |
2 | | -
|
3 | | -Implements the HMAC algorithm as described by RFC 2104. |
4 | | -""" |
5 | | - |
6 | | -import warnings as _warnings |
7 | | - |
8 | | -# from _operator import _compare_digest as compare_digest |
9 | | -import hashlib as _hashlib |
10 | | - |
11 | | -PendingDeprecationWarning = None |
12 | | -RuntimeWarning = None |
13 | | - |
14 | | -trans_5C = bytes((x ^ 0x5C) for x in range(256)) |
15 | | -trans_36 = bytes((x ^ 0x36) for x in range(256)) |
16 | | - |
17 | | - |
18 | | -def translate(d, t): |
19 | | - return bytes(t[x] for x in d) |
20 | | - |
21 | | - |
22 | | -# The size of the digests returned by HMAC depends on the underlying |
23 | | -# hashing module used. Use digest_size from the instance of HMAC instead. |
24 | | -digest_size = None |
| 1 | +# Implements the hmac module from the Python standard library. |
25 | 2 |
|
26 | 3 |
|
27 | 4 | class HMAC: |
28 | | - """RFC 2104 HMAC class. Also complies with RFC 4231. |
29 | | -
|
30 | | - This supports the API for Cryptographic Hash Functions (PEP 247). |
31 | | - """ |
32 | | - |
33 | | - blocksize = 64 # 512-bit HMAC; can be changed in subclasses. |
34 | | - |
35 | 5 | def __init__(self, key, msg=None, digestmod=None): |
36 | | - """Create a new HMAC object. |
37 | | -
|
38 | | - key: key for the keyed hash object. |
39 | | - msg: Initial input for the hash, if provided. |
40 | | - digestmod: A module supporting PEP 247. *OR* |
41 | | - A hashlib constructor returning a new hash object. *OR* |
42 | | - A hash name suitable for hashlib.new(). |
43 | | - Defaults to hashlib.md5. |
44 | | - Implicit default to hashlib.md5 is deprecated and will be |
45 | | - removed in Python 3.6. |
46 | | -
|
47 | | - Note: key and msg must be a bytes or bytearray objects. |
48 | | - """ |
49 | | - |
50 | 6 | if not isinstance(key, (bytes, bytearray)): |
51 | | - raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) |
| 7 | + raise TypeError("key: expected bytes/bytearray") |
| 8 | + |
| 9 | + import hashlib |
52 | 10 |
|
53 | 11 | if digestmod is None: |
54 | | - _warnings.warn( |
55 | | - "HMAC() without an explicit digestmod argument " "is deprecated.", |
56 | | - PendingDeprecationWarning, |
57 | | - 2, |
58 | | - ) |
59 | | - digestmod = _hashlib.md5 |
| 12 | + # TODO: Default hash algorithm is now deprecated. |
| 13 | + digestmod = hashlib.md5 |
60 | 14 |
|
61 | 15 | if callable(digestmod): |
62 | | - self.digest_cons = digestmod |
| 16 | + # A hashlib constructor returning a new hash object. |
| 17 | + make_hash = digestmod # A |
63 | 18 | elif isinstance(digestmod, str): |
64 | | - self.digest_cons = lambda d=b"": _hashlib.new(digestmod, d) |
65 | | - else: |
66 | | - self.digest_cons = lambda d=b"": digestmod.new(d) |
67 | | - |
68 | | - self.outer = self.digest_cons() |
69 | | - self.inner = self.digest_cons() |
70 | | - self.digest_size = self.inner.digest_size |
71 | | - |
72 | | - if hasattr(self.inner, "block_size"): |
73 | | - blocksize = self.inner.block_size |
74 | | - if blocksize < 16: |
75 | | - _warnings.warn( |
76 | | - "block_size of %d seems too small; using our " |
77 | | - "default of %d." % (blocksize, self.blocksize), |
78 | | - RuntimeWarning, |
79 | | - 2, |
80 | | - ) |
81 | | - blocksize = self.blocksize |
| 19 | + # A hash name suitable for hashlib.new(). |
| 20 | + make_hash = lambda d=b"": hashlib.new(digestmod, d) # B |
82 | 21 | else: |
83 | | - _warnings.warn( |
84 | | - "No block_size attribute on given digest object; " |
85 | | - "Assuming %d." % (self.blocksize), |
86 | | - RuntimeWarning, |
87 | | - 2, |
88 | | - ) |
89 | | - blocksize = self.blocksize |
90 | | - |
91 | | - # self.blocksize is the default blocksize. self.block_size is |
92 | | - # effective block size as well as the public API attribute. |
93 | | - self.block_size = blocksize |
94 | | - |
95 | | - if len(key) > blocksize: |
96 | | - key = self.digest_cons(key).digest() |
97 | | - |
98 | | - key = key + bytes(blocksize - len(key)) |
99 | | - self.outer.update(translate(key, trans_5C)) |
100 | | - self.inner.update(translate(key, trans_36)) |
| 22 | + # A module supporting PEP 247. |
| 23 | + make_hash = digestmod.new # C |
| 24 | + |
| 25 | + self._outer = make_hash() |
| 26 | + self._inner = make_hash() |
| 27 | + |
| 28 | + self.digest_size = getattr(self._inner, "digest_size", None) |
| 29 | + # If the provided hash doesn't support block_size (e.g. built-in |
| 30 | + # hashlib), 64 is the correct default for all built-in hash |
| 31 | + # functions (md5, sha1, sha256). |
| 32 | + self.block_size = getattr(self._inner, "block_size", 64) |
| 33 | + |
| 34 | + # Truncate to digest_size if greater than block_size. |
| 35 | + if len(key) > self.block_size: |
| 36 | + key = make_hash(key).digest() |
| 37 | + |
| 38 | + # Pad to block size. |
| 39 | + key = key + bytes(self.block_size - len(key)) |
| 40 | + |
| 41 | + self._outer.update(bytes(x ^ 0x5C for x in key)) |
| 42 | + self._inner.update(bytes(x ^ 0x36 for x in key)) |
| 43 | + |
101 | 44 | if msg is not None: |
102 | 45 | self.update(msg) |
103 | 46 |
|
104 | 47 | @property |
105 | 48 | def name(self): |
106 | | - return "hmac-" + self.inner.name |
| 49 | + return "hmac-" + getattr(self._inner, "name", type(self._inner).__name__) |
107 | 50 |
|
108 | 51 | def update(self, msg): |
109 | | - """Update this hashing object with the string msg.""" |
110 | | - self.inner.update(msg) |
| 52 | + self._inner.update(msg) |
111 | 53 |
|
112 | 54 | def copy(self): |
113 | | - """Return a separate copy of this hashing object. |
114 | | -
|
115 | | - An update to this copy won't affect the original object. |
116 | | - """ |
| 55 | + if not hasattr(self._inner, "copy"): |
| 56 | + # Not supported for built-in hash functions. |
| 57 | + raise NotImplementedError() |
117 | 58 | # Call __new__ directly to avoid the expensive __init__. |
118 | 59 | other = self.__class__.__new__(self.__class__) |
119 | | - other.digest_cons = self.digest_cons |
| 60 | + other.block_size = self.block_size |
120 | 61 | other.digest_size = self.digest_size |
121 | | - other.inner = self.inner.copy() |
122 | | - other.outer = self.outer.copy() |
| 62 | + other._inner = self._inner.copy() |
| 63 | + other._outer = self._outer.copy() |
123 | 64 | return other |
124 | 65 |
|
125 | 66 | def _current(self): |
126 | | - """Return a hash object for the current state. |
127 | | -
|
128 | | - To be used only internally with digest() and hexdigest(). |
129 | | - """ |
130 | | - h = self.outer.copy() |
131 | | - h.update(self.inner.digest()) |
| 67 | + h = self._outer |
| 68 | + if hasattr(h, "copy"): |
| 69 | + # built-in hash functions don't support this, and as a result, |
| 70 | + # digest() will finalise the hmac and further calls to |
| 71 | + # update/digest will fail. |
| 72 | + h = h.copy() |
| 73 | + h.update(self._inner.digest()) |
132 | 74 | return h |
133 | 75 |
|
134 | 76 | def digest(self): |
135 | | - """Return the hash value of this hashing object. |
136 | | -
|
137 | | - This returns a string containing 8-bit data. The object is |
138 | | - not altered in any way by this function; you can continue |
139 | | - updating the object after calling this function. |
140 | | - """ |
141 | 77 | h = self._current() |
142 | 78 | return h.digest() |
143 | 79 |
|
144 | 80 | def hexdigest(self): |
145 | | - """Like digest(), but returns a string of hexadecimal digits instead.""" |
146 | | - h = self._current() |
147 | | - return h.hexdigest() |
| 81 | + import binascii |
148 | 82 |
|
| 83 | + return str(binascii.hexlify(self.digest()), "utf-8") |
149 | 84 |
|
150 | | -def new(key, msg=None, digestmod=None): |
151 | | - """Create a new hashing object and return it. |
152 | | -
|
153 | | - key: The starting key for the hash. |
154 | | - msg: if available, will immediately be hashed into the object's starting |
155 | | - state. |
156 | 85 |
|
157 | | - You can now feed arbitrary strings into the object using its update() |
158 | | - method, and can ask for the hash value at any time by calling its digest() |
159 | | - method. |
160 | | - """ |
| 86 | +def new(key, msg=None, digestmod=None): |
161 | 87 | return HMAC(key, msg, digestmod) |
0 commit comments