Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 12c9d02

Browse files
committed
Fixes Issue #12059: Properly handle missing hash functions even when
the expected builtin modules are not present. This includes a unittest for __get_builtin_constructor() in the face of such an error.
1 parent e670c88 commit 12c9d02

2 files changed

Lines changed: 41 additions & 20 deletions

File tree

Lib/hashlib.py

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,26 +64,29 @@
6464

6565

6666
def __get_builtin_constructor(name):
67-
if name in ('SHA1', 'sha1'):
68-
import _sha1
69-
return _sha1.sha1
70-
elif name in ('MD5', 'md5'):
71-
import _md5
72-
return _md5.md5
73-
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
74-
import _sha256
75-
bs = name[3:]
76-
if bs == '256':
77-
return _sha256.sha256
78-
elif bs == '224':
79-
return _sha256.sha224
80-
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
81-
import _sha512
82-
bs = name[3:]
83-
if bs == '512':
84-
return _sha512.sha512
85-
elif bs == '384':
86-
return _sha512.sha384
67+
try:
68+
if name in ('SHA1', 'sha1'):
69+
import _sha1
70+
return _sha1.sha1
71+
elif name in ('MD5', 'md5'):
72+
import _md5
73+
return _md5.md5
74+
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
75+
import _sha256
76+
bs = name[3:]
77+
if bs == '256':
78+
return _sha256.sha256
79+
elif bs == '224':
80+
return _sha256.sha224
81+
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
82+
import _sha512
83+
bs = name[3:]
84+
if bs == '512':
85+
return _sha512.sha512
86+
elif bs == '384':
87+
return _sha512.sha384
88+
except ImportError:
89+
pass # no extension module, this hash is unsupported.
8790

8891
raise ValueError('unsupported hash type %s' % name)
8992

Lib/test/test_hashlib.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,24 @@ def test_unknown_hash(self):
118118
else:
119119
self.assertTrue(0 == "hashlib didn't reject bogus hash name")
120120

121+
def test_get_builtin_constructor(self):
122+
get_builtin_constructor = hashlib.__dict__[
123+
'__get_builtin_constructor']
124+
self.assertRaises(ValueError, get_builtin_constructor, 'test')
125+
try:
126+
import _md5
127+
except ImportError:
128+
pass
129+
# This forces an ImportError for "import _md5" statements
130+
sys.modules['_md5'] = None
131+
try:
132+
self.assertRaises(ValueError, get_builtin_constructor, 'md5')
133+
finally:
134+
if '_md5' in locals():
135+
sys.modules['_md5'] = _md5
136+
else:
137+
del sys.modules['_md5']
138+
121139
def test_hexdigest(self):
122140
for name in self.supported_hash_names:
123141
h = hashlib.new(name)

0 commit comments

Comments
 (0)