|
1 | 1 | from __future__ import absolute_import |
2 | 2 |
|
| 3 | +import hashlib |
3 | 4 | import hmac |
4 | 5 | import os |
5 | 6 | import sys |
6 | 7 | import warnings |
7 | 8 | from binascii import hexlify, unhexlify |
8 | | -from hashlib import md5, sha1, sha256 |
9 | 9 |
|
10 | 10 | from ..exceptions import ( |
11 | 11 | InsecurePlatformWarning, |
|
24 | 24 | ALPN_PROTOCOLS = ["http/1.1"] |
25 | 25 |
|
26 | 26 | # Maps the length of a digest to a possible hash function producing this digest |
27 | | -HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256} |
| 27 | +HASHFUNC_MAP = { |
| 28 | + length: getattr(hashlib, algorithm, None) |
| 29 | + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) |
| 30 | +} |
28 | 31 |
|
29 | 32 |
|
30 | 33 | def _const_compare_digest_backport(a, b): |
@@ -191,9 +194,15 @@ def assert_fingerprint(cert, fingerprint): |
191 | 194 |
|
192 | 195 | fingerprint = fingerprint.replace(":", "").lower() |
193 | 196 | digest_length = len(fingerprint) |
194 | | - hashfunc = HASHFUNC_MAP.get(digest_length) |
195 | | - if not hashfunc: |
| 197 | + if digest_length not in HASHFUNC_MAP: |
196 | 198 | raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) |
| 199 | + hashfunc = HASHFUNC_MAP.get(digest_length) |
| 200 | + if hashfunc is None: |
| 201 | + raise SSLError( |
| 202 | + "Hash function implementation unavailable for fingerprint length: {0}".format( |
| 203 | + digest_length |
| 204 | + ) |
| 205 | + ) |
197 | 206 |
|
198 | 207 | # We need encode() here for py32; works on py2 and p33. |
199 | 208 | fingerprint_bytes = unhexlify(fingerprint.encode()) |
|
0 commit comments