Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

hmac.py 6.4 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
  1. """HMAC (Keyed-Hashing for Message Authentication) Python module.
  2. Implements the HMAC algorithm as described by RFC 2104.
  3. """
  4. import warnings as _warnings
  5. from _operator import _compare_digest as compare_digest
  6. try:
  7. import _hashlib as _hashopenssl
  8. except ImportError:
  9. _hashopenssl = None
  10. _openssl_md_meths = None
  11. else:
  12. _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
  13. import hashlib as _hashlib
  14. trans_5C = bytes((x ^ 0x5C) for x in range(256))
  15. trans_36 = bytes((x ^ 0x36) for x in range(256))
  16. # The size of the digests returned by HMAC depends on the underlying
  17. # hashing module used. Use digest_size from the instance of HMAC instead.
  18. digest_size = None
  19. class HMAC:
  20. """RFC 2104 HMAC class. Also complies with RFC 4231.
  21. This supports the API for Cryptographic Hash Functions (PEP 247).
  22. """
  23. blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
  24. def __init__(self, key, msg = None, digestmod = None):
  25. """Create a new HMAC object.
  26. key: key for the keyed hash object.
  27. msg: Initial input for the hash, if provided.
  28. digestmod: A module supporting PEP 247. *OR*
  29. A hashlib constructor returning a new hash object. *OR*
  30. A hash name suitable for hashlib.new().
  31. Defaults to hashlib.md5.
  32. Implicit default to hashlib.md5 is deprecated since Python
  33. 3.4 and will be removed in Python 3.8.
  34. Note: key and msg must be a bytes or bytearray objects.
  35. """
  36. if not isinstance(key, (bytes, bytearray)):
  37. raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
  38. if digestmod is None:
  39. _warnings.warn("HMAC() without an explicit digestmod argument "
  40. "is deprecated since Python 3.4, and will be removed "
  41. "in 3.8",
  42. DeprecationWarning, 2)
  43. digestmod = _hashlib.md5
  44. if callable(digestmod):
  45. self.digest_cons = digestmod
  46. elif isinstance(digestmod, str):
  47. self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
  48. else:
  49. self.digest_cons = lambda d=b'': digestmod.new(d)
  50. self.outer = self.digest_cons()
  51. self.inner = self.digest_cons()
  52. self.digest_size = self.inner.digest_size
  53. if hasattr(self.inner, 'block_size'):
  54. blocksize = self.inner.block_size
  55. if blocksize < 16:
  56. _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. # self.blocksize is the default blocksize. self.block_size is
  66. # effective block size as well as the public API attribute.
  67. self.block_size = blocksize
  68. if len(key) > blocksize:
  69. key = self.digest_cons(key).digest()
  70. key = key.ljust(blocksize, b'\0')
  71. self.outer.update(key.translate(trans_5C))
  72. self.inner.update(key.translate(trans_36))
  73. if msg is not None:
  74. self.update(msg)
  75. @property
  76. def name(self):
  77. return "hmac-" + self.inner.name
  78. def update(self, msg):
  79. """Update this hashing object with the string msg.
  80. """
  81. self.inner.update(msg)
  82. def copy(self):
  83. """Return a separate copy of this hashing object.
  84. An update to this copy won't affect the original object.
  85. """
  86. # Call __new__ directly to avoid the expensive __init__.
  87. other = self.__class__.__new__(self.__class__)
  88. other.digest_cons = self.digest_cons
  89. other.digest_size = self.digest_size
  90. other.inner = self.inner.copy()
  91. other.outer = self.outer.copy()
  92. return other
  93. def _current(self):
  94. """Return a hash object for the current state.
  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. def digest(self):
  101. """Return the hash value of this hashing object.
  102. This returns a string containing 8-bit data. The object is
  103. not altered in any way by this function; you can continue
  104. updating the object after calling this function.
  105. """
  106. h = self._current()
  107. return h.digest()
  108. def hexdigest(self):
  109. """Like digest(), but returns a string of hexadecimal digits instead.
  110. """
  111. h = self._current()
  112. return h.hexdigest()
  113. def new(key, msg = None, digestmod = None):
  114. """Create a new hashing object and return it.
  115. key: The starting key for the hash.
  116. msg: if available, will immediately be hashed into the object's starting
  117. state.
  118. You can now feed arbitrary strings into the object using its update()
  119. method, and can ask for the hash value at any time by calling its digest()
  120. method.
  121. """
  122. return HMAC(key, msg, digestmod)
  123. def digest(key, msg, digest):
  124. """Fast inline implementation of HMAC
  125. key: key for the keyed hash object.
  126. msg: input message
  127. digest: A hash name suitable for hashlib.new() for best performance. *OR*
  128. A hashlib constructor returning a new hash object. *OR*
  129. A module supporting PEP 247.
  130. Note: key and msg must be a bytes or bytearray objects.
  131. """
  132. if (_hashopenssl is not None and
  133. isinstance(digest, str) and digest in _openssl_md_meths):
  134. return _hashopenssl.hmac_digest(key, msg, digest)
  135. if callable(digest):
  136. digest_cons = digest
  137. elif isinstance(digest, str):
  138. digest_cons = lambda d=b'': _hashlib.new(digest, d)
  139. else:
  140. digest_cons = lambda d=b'': digest.new(d)
  141. inner = digest_cons()
  142. outer = digest_cons()
  143. blocksize = getattr(inner, 'block_size', 64)
  144. if len(key) > blocksize:
  145. key = digest_cons(key).digest()
  146. key = key + b'\x00' * (blocksize - len(key))
  147. inner.update(key.translate(trans_36))
  148. outer.update(key.translate(trans_5C))
  149. inner.update(msg)
  150. outer.update(inner.digest())
  151. return outer.digest()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...