Skip to content

Commit fb1d60c

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 0cc4fd9 commit fb1d60c

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 _sha
69-
return _sha.new
70-
elif name in ('MD5', 'md5'):
71-
import _md5
72-
return _md5.new
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 _sha
70+
return _sha.new
71+
elif name in ('MD5', 'md5'):
72+
import _md5
73+
return _md5.new
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
@@ -115,6 +115,24 @@ def test_unknown_hash(self):
115115
else:
116116
self.assertTrue(0 == "hashlib didn't reject bogus hash name")
117117

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

0 commit comments

Comments
 (0)