mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
Make hmac use bytes. Make test_hmac pass.
This commit is contained in:
parent
f895307a94
commit
3f42908051
2 changed files with 37 additions and 26 deletions
19
Lib/hmac.py
19
Lib/hmac.py
|
@ -3,8 +3,8 @@
|
|||
Implements the HMAC algorithm as described by RFC 2104.
|
||||
"""
|
||||
|
||||
trans_5C = "".join ([chr (x ^ 0x5C) for x in range(256)])
|
||||
trans_36 = "".join ([chr (x ^ 0x36) for x in range(256)])
|
||||
trans_5C = bytes((x ^ 0x5C) for x in range(256))
|
||||
trans_36 = bytes((x ^ 0x36) for x in range(256))
|
||||
|
||||
# The size of the digests returned by HMAC depends on the underlying
|
||||
# hashing module used. Use digest_size from the instance of HMAC instead.
|
||||
|
@ -30,11 +30,18 @@ class HMAC:
|
|||
digestmod: A module supporting PEP 247. *OR*
|
||||
A hashlib constructor returning a new hash object.
|
||||
Defaults to hashlib.md5.
|
||||
|
||||
Note: key and msg must be bytes objects.
|
||||
"""
|
||||
|
||||
if key is _secret_backdoor_key: # cheap
|
||||
return
|
||||
|
||||
if not isinstance(key, bytes):
|
||||
if hasattr(key, "__index__"):
|
||||
raise TypeError("key can't be a number")
|
||||
key = bytes(key)
|
||||
|
||||
if digestmod is None:
|
||||
import hashlib
|
||||
digestmod = hashlib.md5
|
||||
|
@ -42,7 +49,7 @@ class HMAC:
|
|||
if hasattr(digestmod, '__call__'):
|
||||
self.digest_cons = digestmod
|
||||
else:
|
||||
self.digest_cons = lambda d='': digestmod.new(d)
|
||||
self.digest_cons = lambda d=b'': digestmod.new(d)
|
||||
|
||||
self.outer = self.digest_cons()
|
||||
self.inner = self.digest_cons()
|
||||
|
@ -52,7 +59,7 @@ class HMAC:
|
|||
if len(key) > blocksize:
|
||||
key = self.digest_cons(key).digest()
|
||||
|
||||
key = key + chr(0) * (blocksize - len(key))
|
||||
key = key + bytes(blocksize - len(key))
|
||||
self.outer.update(key.translate(trans_5C))
|
||||
self.inner.update(key.translate(trans_36))
|
||||
if msg is not None:
|
||||
|
@ -64,6 +71,10 @@ class HMAC:
|
|||
def update(self, msg):
|
||||
"""Update this hashing object with the string msg.
|
||||
"""
|
||||
if not isinstance(msg, bytes):
|
||||
if hasattr(msg, "__index__"):
|
||||
raise TypeError("msg can't be a number")
|
||||
msg = bytes(msg)
|
||||
self.inner.update(msg)
|
||||
|
||||
def copy(self):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue