def _do_kat_aes_test(self, file_name, segment_size): test_vectors = load_test_vectors(("Cipher", "AES"), file_name, "AES CFB%d KAT" % segment_size, { "count" : lambda x: int(x) } ) if test_vectors is None: return direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc cipher = AES.new(tv.key, AES.MODE_CFB, tv.iv, segment_size=segment_size) if direction == "[ENCRYPT]": self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext) elif direction == "[DECRYPT]": self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext) else: assert False
def _do_tdes_test(self, file_name, segment_size): test_vectors = load_test_vectors(("Cipher", "TDES"), file_name, "TDES CFB%d KAT" % segment_size, { "count" : lambda x: int(x) } ) if test_vectors is None: return direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc if hasattr(tv, "keys"): cipher = DES.new(tv.keys, DES.MODE_CFB, tv.iv, segment_size=segment_size) else: if tv.key1 != tv.key3: key = tv.key1 + tv.key2 + tv.key3 # Option 3 else: key = tv.key1 + tv.key2 # Option 2 cipher = DES3.new(key, DES3.MODE_CFB, tv.iv, segment_size=segment_size) if direction == "[ENCRYPT]": self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext) elif direction == "[DECRYPT]": self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext) else: assert False
def get_tests(config={}): from Crypto.Hash import SHA1 from .common import make_hash_tests tests = [] test_vectors = load_test_vectors( ("Hash", "SHA1"), "SHA1ShortMsg.rsp", "KAT SHA-1", {"len": lambda x: int(x)}) or [] test_data = test_data_various[:] for tv in test_vectors: try: if tv.startswith('['): continue except AttributeError: pass if tv.len == 0: tv.msg = b"" test_data.append((hexlify(tv.md), tv.msg, tv.desc)) tests = make_hash_tests(SHA1, "SHA1", test_data, digest_size=20, oid="1.3.14.3.2.26") return tests
def _do_mct_aes_test(self, file_name): test_vectors = load_test_vectors(("Cipher", "AES"), file_name, "AES CBC Montecarlo", {"count": lambda x: int(x)}) if test_vectors is None: return direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc cipher = AES.new(tv.key, self.aes_mode, tv.iv) if direction == '[ENCRYPT]': cts = [tv.iv] for count in range(1000): cts.append(cipher.encrypt(tv.plaintext)) tv.plaintext = cts[-2] self.assertEqual(cts[-1], tv.ciphertext) elif direction == '[DECRYPT]': pts = [tv.iv] for count in range(1000): pts.append(cipher.decrypt(tv.ciphertext)) tv.ciphertext = pts[-2] self.assertEqual(pts[-1], tv.plaintext) else: assert False
def _do_mct_aes_test(self, file_name, segment_size): test_vectors = load_test_vectors(("Cipher", "AES"), file_name, "AES CFB%d Montecarlo" % segment_size, {"count": lambda x: int(x)}) if test_vectors is None: return assert (segment_size in (8, 128)) direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc cipher = AES.new(tv.key, AES.MODE_CFB, tv.iv, segment_size=segment_size) def get_input(input_text, output_seq, j): # CFB128 if segment_size == 128: if j >= 2: return output_seq[-2] return [input_text, tv.iv][j] # CFB8 if j == 0: return input_text elif j <= 16: return tv.iv[j - 1:j] return output_seq[j - 17] if direction == '[ENCRYPT]': cts = [] for j in range(1000): plaintext = get_input(tv.plaintext, cts, j) cts.append(cipher.encrypt(plaintext)) self.assertEqual(cts[-1], tv.ciphertext) elif direction == '[DECRYPT]': pts = [] for j in range(1000): ciphertext = get_input(tv.ciphertext, pts, j) pts.append(cipher.decrypt(ciphertext)) self.assertEqual(pts[-1], tv.plaintext) else: assert False
def get_tests(config={}): from .common import make_hash_tests tests = [] test_vectors = load_test_vectors(("Hash", "SHA3"), "ShortMsgKAT_SHA3-512.txt", "KAT SHA-3 512", { "len" : lambda x: int(x) } ) or [] test_data = [] for tv in test_vectors: if tv.len == 0: tv.msg = b("") test_data.append((hexlify(tv.md), tv.msg, tv.desc)) tests += make_hash_tests(SHA3, "SHA3_512", test_data, digest_size=SHA3.digest_size, oid="2.16.840.1.101.3.4.2.10") tests += list_test_cases(APITest) return tests
def get_tests_SHA512(): test_vectors = load_test_vectors( ("Hash", "SHA2"), "SHA512ShortMsg.rsp", "KAT SHA-512", {"len": lambda x: int(x)}) or [] test_data = test_data_512_other[:] for tv in test_vectors: try: if tv.startswith('['): continue except AttributeError: pass if tv.len == 0: tv.msg = b"" test_data.append((hexlify(tv.md), tv.msg, tv.desc)) tests = make_hash_tests(SHA512, "SHA512", test_data, digest_size=64, oid="2.16.840.1.101.3.4.2.3") return tests
def get_tests_SHA512_224(): test_vectors = load_test_vectors( ("Hash", "SHA2"), "SHA512_224ShortMsg.rsp", "KAT SHA-512/224", {"len": lambda x: int(x)}) or [] test_data = [] for tv in test_vectors: try: if tv.startswith('['): continue except AttributeError: pass if tv.len == 0: tv.msg = b"" test_data.append((hexlify(tv.md), tv.msg, tv.desc)) tests = make_hash_tests(SHA512, "SHA512/224", test_data, digest_size=28, oid="2.16.840.1.101.3.4.2.5", extra_params={"truncate": "224"}) return tests
vector_files = [ ("ShortMsgSamples_cSHAKE128.txt", "Short Message Samples cSHAKE128", "128_cshake", cSHAKE128), ("ShortMsgSamples_cSHAKE256.txt", "Short Message Samples cSHAKE256", "256_cshake", cSHAKE256), ("CustomMsgSamples_cSHAKE128.txt", "Custom Message Samples cSHAKE128", "custom_128_cshake", cSHAKE128), ("CustomMsgSamples_cSHAKE256.txt", "Custom Message Samples cSHAKE256", "custom_256_cshake", cSHAKE256), ] for file, descr, tag, test_class in vector_files: test_vectors = load_test_vectors( ("Hash", "SHA3"), file, descr, { "len": lambda x: int(x), "nlen": lambda x: int(x), "slen": lambda x: int(x) }) or [] for idx, tv in enumerate(test_vectors): if getattr(tv, "len", 0) == 0: data = b("") else: data = tobytes(tv.msg) assert (tv.len == len(tv.msg) * 8) if getattr(tv, "nlen", 0) != 0: raise ValueError("Unsupported cSHAKE test vector") if getattr(tv, "slen", 0) == 0: custom = b("") else: custom = tobytes(tv.s)
class SHAKE128Test(SHAKETest): shake = SHAKE128 class SHAKE256Test(SHAKETest): shake = SHAKE256 class SHAKEVectors(unittest.TestCase): pass test_vectors_128 = load_test_vectors( ("Hash", "SHA3"), "ShortMsgKAT_SHAKE128.txt", "Short Messages KAT SHAKE128", {"len": lambda x: int(x)}) or [] for idx, tv in enumerate(test_vectors_128): if tv.len == 0: data = b("") else: data = tobytes(tv.msg) def new_test(self, data=data, result=tv.md): hobj = SHAKE128.new(data=data) digest = hobj.read(len(result)) self.assertEqual(digest, result) setattr(SHAKEVectors, "test_128_%d" % idx, new_test)
class NISTTestVectorsGCM(unittest.TestCase): def __init__(self, a): self.use_clmul = True unittest.TestCase.__init__(self, a) class NISTTestVectorsGCM_no_clmul(unittest.TestCase): def __init__(self, a): self.use_clmul = False unittest.TestCase.__init__(self, a) test_vectors_nist = load_test_vectors( ("Cipher", "AES"), "gcmDecrypt128.rsp", "GCM decrypt", {"count": lambda x: int(x)}) or [] test_vectors_nist += load_test_vectors( ("Cipher", "AES"), "gcmEncryptExtIV128.rsp", "GCM encrypt", {"count": lambda x: int(x)}) or [] for idx, tv in enumerate(test_vectors_nist): # The test vector file contains some directive lines if isinstance(tv, str): continue def single_test(self, tv=tv): self.description = tv.desc
h = keccak.new(digest_bits=512, data=msg[:4], update_after_digest=True) self.assertEqual(h.digest(), dig1) # ... and the subsequent digest applies to the entire message # up to that point h.update(msg[4:]) self.assertEqual(h.digest(), dig2) class KeccakVectors(unittest.TestCase): pass # TODO: add ExtremelyLong tests test_vectors_224 = load_test_vectors( ("Hash", "keccak"), "ShortMsgKAT_224.txt", "Short Messages KAT 224", {"len": lambda x: int(x)}) or [] test_vectors_224 += load_test_vectors( ("Hash", "keccak"), "LongMsgKAT_224.txt", "Long Messages KAT 224", {"len": lambda x: int(x)}) or [] for idx, tv in enumerate(test_vectors_224): if tv.len == 0: data = b("") else: data = tobytes(tv.msg) def new_test(self, data=data, result=tv.md): hobj = keccak.new(digest_bits=224, data=data) self.assertEqual(hobj.digest(), result)
verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng) self.assertRaises(ValueError, verifier.verify, hashed, signature) def test_can_sign(self): test_public_key = RSA.generate(1024).public_key() verifier = pss.new(test_public_key) self.assertEqual(verifier.can_sign(), False) class FIPS_PKCS1_Verify_Tests_KAT(unittest.TestCase): pass test_vectors_verify = load_test_vectors( ("Signature", "PKCS1-PSS"), "SigVerPSS_186-3.rsp", "Signature Verification 186-3", { 'shaalg': lambda x: x, 'result': lambda x: x }) or [] for count, tv in enumerate(test_vectors_verify): if isinstance(tv, str): continue if hasattr(tv, "n"): modulus = tv.n continue if hasattr(tv, "p"): continue hash_module = load_hash_by_name(tv.shaalg.upper()) hash_obj = hash_module.new(tv.msg) public_key = RSA.construct([bytes_to_long(x)
'0123456789abcdef23456789abcdef01456789abcdef0123', 'NIST SP800-67 B.1'), # This test is designed to test the DES3 API, not the correctness of the # output. ('21e81b7ade88a259', '5c577d4d9b20c0f8', '9b397ebf81b1181e282f4bb8adbadc6b', 'Two-key 3DES'), ] # NIST CAVP test vectors nist_tdes_mmt_files = ("TECBMMT2.rsp", "TECBMMT3.rsp") for tdes_file in nist_tdes_mmt_files: test_vectors = load_test_vectors( ("Cipher", "TDES"), tdes_file, "TDES ECB (%s)" % tdes_file, {"count": lambda x: int(x)}) or [] for index, tv in enumerate(test_vectors): # The test vector file contains some directive lines if isinstance(tv, str): continue key = tv.key1 + tv.key2 + tv.key3 test_data_item = (tostr(hexlify(tv.plaintext)), tostr(hexlify(tv.ciphertext)), tostr(hexlify(key)), "%s (%s)" % (tdes_file, index)) test_data.append(test_data_item)
def test_sizes(self): self.assertEqual(self.pointS.size_in_bits(), 521) self.assertEqual(self.pointS.size_in_bytes(), 66) class TestEccPoint_PAI_P224(unittest.TestCase): """Test vectors from http://point-at-infinity.org/ecc/nisttv""" curve = _curves['p224'] pointG = EccPoint(curve.Gx, curve.Gy, "p224") tv_pai = load_test_vectors(("PublicKey", "ECC"), "point-at-infinity.org-P224.txt", "P-224 tests from point-at-infinity.org", {"k": lambda k: int(k), "x": lambda x: int(x, 16), "y": lambda y: int(y, 16)}) or [] for tv in tv_pai: def new_test(self, scalar=tv.k, x=tv.x, y=tv.y): result = self.pointG * scalar self.assertEqual(result.x, x) self.assertEqual(result.y, y) setattr(TestEccPoint_PAI_P224, "test_%d" % tv.count, new_test) class TestEccPoint_PAI_P256(unittest.TestCase): """Test vectors from http://point-at-infinity.org/ecc/nisttv""" curve = _curves['p256'] pointG = EccPoint(curve.Gx, curve.Gy, "p256")
"""Verify public/private method""" self.description = "can_sign() test" signer = DSS.new(self.key_priv, 'fips-186-3') self.failUnless(signer.can_sign()) signer = DSS.new(self.key_pub, 'fips-186-3') self.failIf(signer.can_sign()) class FIPS_DSA_Tests_KAT(unittest.TestCase): pass test_vectors_verify = load_test_vectors( ("Signature", "DSA"), "FIPS_186_3_SigVer.rsp", "Signature Verification 186-3", {'result': lambda x: x}) or [] for idx, tv in enumerate(test_vectors_verify): if isinstance(tv, str): res = re.match(r"\[mod = L=([0-9]+), N=([0-9]+), ([a-zA-Z0-9-]+)\]", tv) assert (res) hash_name = res.group(3).replace("-", "") hash_module = load_hash_by_name(hash_name) continue if hasattr(tv, "p"): modulus = tv.p generator = tv.g