Skip to content

Commit 175634b

Browse files
committed
hashlib: Reuse classes available in ushashlib, extend tests.
1 parent f8ee045 commit 175634b

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

hashlib/hashlib/__init__.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,22 @@
1-
from ._sha256 import sha224, sha256
2-
from ._sha512 import sha384, sha512
1+
try:
2+
import uhashlib
3+
except ImportError:
4+
uhashlib = None
5+
6+
def init():
7+
for i in ("sha1", "sha224", "sha256", "sha384", "sha512"):
8+
c = getattr(uhashlib, i, None)
9+
if not c:
10+
c = __import__("_" + i, None, None, (), 1)
11+
c = getattr(c, i)
12+
globals()[i] = c
13+
14+
init()
15+
16+
17+
def new(algo, data=b""):
18+
try:
19+
c = globals()[algo]
20+
return c(data)
21+
except KeyError:
22+
raise ValueError(algo)

hashlib/test_hashlib.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,23 @@
44

55
sha256_test()
66
sha512_test()
7-
print("OK")
7+
8+
9+
import hashlib
10+
11+
patterns = [
12+
("sha224", b"1234",
13+
b'\x99\xfb/H\xc6\xafGa\xf9\x04\xfc\x85\xf9^\xb5a\x90\xe5\xd4\x0b\x1fD\xec:\x9c\x1f\xa3\x19'),
14+
15+
("sha256", b"1234",
16+
b'\x03\xacgB\x16\xf3\xe1\\v\x1e\xe1\xa5\xe2U\xf0g\x956#\xc8\xb3\x88\xb4E\x9e\x13\xf9x\xd7\xc8F\xf4'),
17+
18+
("sha384", b"1234",
19+
b'PO\x00\x8c\x8f\xcf\x8b.\xd5\xdf\xcd\xe7R\xfcTd\xab\x8b\xa0d!]\x9c[_\xc4\x86\xaf=\x9a\xb8\xc8\x1b\x14xQ\x80\xd2\xad|\xee\x1a\xb7\x92\xadDy\x8c'),
20+
21+
("sha512", b"1234",
22+
b'\xd4\x04U\x9f`.\xabo\xd6\x02\xacv\x80\xda\xcb\xfa\xad\xd1603^\x95\x1f\tz\xf3\x90\x0e\x9d\xe1v\xb6\xdb(Q/.\x00\x0b\x9d\x04\xfb\xa5\x13>\x8b\x1cn\x8d\xf5\x9d\xb3\xa8\xab\x9d`\xbeK\x97\xcc\x9e\x81\xdb'),
23+
]
24+
25+
for algo, input, output in patterns:
26+
assert hashlib.new(algo, input).digest() == output

0 commit comments

Comments
 (0)