class KDFTests(unittest.TestCase): pbkdf2_test_vectors = [ (b'password', b'salt', 1, None), (b'password', b'salt', 2, None), (b'password', b'salt', 4096, None), # too slow, it takes over a minute on a fast CPU. #(b'password', b'salt', 16777216, None), (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, -1), (b'pass\0word', b'sa\0lt', 4096, 16), ] scrypt_test_vectors = [ (b'', b'', 16, 1, 1, unhexlify( '77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906' )), (b'password', b'NaCl', 1024, 8, 16, unhexlify( 'fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640' )), (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify( '7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887' )), ] pbkdf2_results = { "sha1": [ # official test vectors from RFC 6070 (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None), (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None), (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None), #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None), (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c' 'f2f07038'), 25), (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None), ], "sha256": [ (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837' 'a86548c92ccc35480805987cb70be17b'), None), (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0' '2a303f8ef3c251dfd6e2d85a95474c43'), None), (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d' '962893a001ce4e11a4963873aa98134a'), None), #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089' # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None), (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17' '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40 ), (bytes.fromhex('89b69d0516f829893c696226650a8687'), None), ], "sha512": [ (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5' 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f' '050235d7d68b1da55e63f73b60a57fce'), None), (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071' '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82' 'be67335c77a6068e04112754f27ccf4e'), None), (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8' '7f6902e072f457b5143f30602641b3d55cd335988cb36b84' '376060ecd532e039b742a239434af2d5'), None), (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8' '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30' '225c583a186cd82bd4daea9724a3d3b8'), 64), (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None), ], } def _test_pbkdf2_hmac(self, pbkdf2, supported): for digest_name, results in self.pbkdf2_results.items(): if digest_name not in supported: continue for i, vector in enumerate(self.pbkdf2_test_vectors): password, salt, rounds, dklen = vector expected, overwrite_dklen = results[i] if overwrite_dklen: dklen = overwrite_dklen out = pbkdf2(digest_name, password, salt, rounds, dklen) self.assertEqual(out, expected, (digest_name, password, salt, rounds, dklen)) out = pbkdf2(digest_name, memoryview(password), memoryview(salt), rounds, dklen) self.assertEqual(out, expected) out = pbkdf2(digest_name, bytearray(password), bytearray(salt), rounds, dklen) self.assertEqual(out, expected) if dklen is None: out = pbkdf2(digest_name, password, salt, rounds) self.assertEqual(out, expected, (digest_name, password, salt, rounds)) with self.assertRaisesRegex(ValueError, '.*unsupported.*'): pbkdf2('unknown', b'pass', b'salt', 1) if 'sha1' in supported: self.assertRaises(TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1) self.assertRaises(TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1) out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt', iterations=1, dklen=None) self.assertEqual(out, self.pbkdf2_results['sha1'][0][0]) @unittest.skipIf(builtin_hashlib is None, "test requires builtin_hashlib") def test_pbkdf2_hmac_py(self): with warnings_helper.check_warnings(): self._test_pbkdf2_hmac(builtin_hashlib.pbkdf2_hmac, builtin_hashes) @unittest.skipUnless(hasattr(openssl_hashlib, 'pbkdf2_hmac'), ' test requires OpenSSL > 1.0') def test_pbkdf2_hmac_c(self): self._test_pbkdf2_hmac(openssl_hashlib.pbkdf2_hmac, openssl_md_meth_names) @unittest.skipUnless(hasattr(hashlib, 'scrypt'), ' test requires OpenSSL > 1.1') @unittest.skipIf(get_fips_mode(), reason="scrypt is blocked in FIPS mode") def test_scrypt(self): for password, salt, n, r, p, expected in self.scrypt_test_vectors: result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p) self.assertEqual(result, expected) # this values should work hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1) # password and salt must be bytes-like with self.assertRaises(TypeError): hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1) with self.assertRaises(TypeError): hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1) # require keyword args with self.assertRaises(TypeError): hashlib.scrypt(b'password') with self.assertRaises(TypeError): hashlib.scrypt(b'password', b'salt') with self.assertRaises(TypeError): hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt') for n in [-1, 0, 1, None]: with self.assertRaises((ValueError, OverflowError, TypeError)): hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1) for r in [-1, 0, None]: with self.assertRaises((ValueError, OverflowError, TypeError)): hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1) for p in [-1, 0, None]: with self.assertRaises((ValueError, OverflowError, TypeError)): hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p) for maxmem in [-1, None]: with self.assertRaises((ValueError, OverflowError, TypeError)): hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, maxmem=maxmem) for dklen in [-1, None]: with self.assertRaises((ValueError, OverflowError, TypeError)): hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, dklen=dklen) def test_normalized_name(self): self.assertNotIn("blake2b512", hashlib.algorithms_available) self.assertNotIn("sha3-512", hashlib.algorithms_available)
def is_fips_mode(self): return get_fips_mode()
raise new = __py_new __get_hash = __get_builtin_constructor # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA from _hashlib import pbkdf2_hmac try: # OpenSSL's scrypt requires OpenSSL 1.1+ from _hashlib import scrypt except ImportError: pass for __func_name in __always_supported: # try them all, some may not work due to the OpenSSL # version not supporting that algorithm. try: globals()[__func_name] = __get_hash(__func_name) except ValueError: import logging logging.exception('code for hash %s was not found.', __func_name) # Cleanup locals() del __always_supported, __func_name, __get_hash del __hash_new, __get_openssl_constructor if not _hashlib.get_fips_mode(): del __py_new del _hashlib_get_fips_mode
def update(self, msg): """Update this hashing object with the string msg. """ if _hashlibopenssl.get_fips_mode(): raise ValueError('hmac.HMAC is not available in FIPS mode') self.inner.update(msg)
def __init__(self, key, msg=None, digestmod=None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. *OR* A hashlib constructor returning a new hash object. *OR* A hash name suitable for hashlib.new(). Defaults to hashlib.md5. Implicit default to hashlib.md5 is deprecated and will be removed in Python 3.6. Note: key and msg must be a bytes or bytearray objects. """ if _hashlibopenssl.get_fips_mode(): raise ValueError('This class is not available in FIPS mode. ' + 'Use hmac.new().') if not isinstance(key, (bytes, bytearray)): raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) if digestmod is None: _warnings.warn( "HMAC() without an explicit digestmod argument " "is deprecated.", PendingDeprecationWarning, 2) digestmod = _hashlib.md5 if callable(digestmod): self.digest_cons = digestmod elif isinstance(digestmod, str): self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d) else: self.digest_cons = lambda d=b'': digestmod.new(d) self.outer = self.digest_cons() self.inner = self.digest_cons() self.digest_size = self.inner.digest_size if hasattr(self.inner, 'block_size'): blocksize = self.inner.block_size if blocksize < 16: _warnings.warn( 'block_size of %d seems too small; using our ' 'default of %d.' % (blocksize, self.blocksize), RuntimeWarning, 2) blocksize = self.blocksize else: _warnings.warn( 'No block_size attribute on given digest object; ' 'Assuming %d.' % (self.blocksize), RuntimeWarning, 2) blocksize = self.blocksize # self.blocksize is the default blocksize. self.block_size is # effective block size as well as the public API attribute. self.block_size = blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key.ljust(blocksize, b'\0') self.outer.update(key.translate(trans_5C)) self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg)
class HMAC_openssl(_hmacopenssl.HMAC): def __new__(cls, key, msg=None, digestmod=None): if not isinstance(key, (bytes, bytearray)): raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) name = _get_openssl_name(digestmod) result = _hmacopenssl.HMAC.__new__(cls, key, digestmod=name) if msg: result.update(msg) return result if _hashlibopenssl.get_fips_mode(): HMAC = HMAC_openssl def new(key, msg=None, digestmod=None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)