Esempio n. 1
0
    def _do_tdes_test(self, file_name):
        test_vectors = load_tests(
            ("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"),
            file_name, "TDES CBC KAT", {"count": lambda x: int(x)})
        assert (test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                direction = tv
                continue

            self.description = tv.desc
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, self.des_mode, tv.iv)
            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, self.des3_mode, tv.iv)

            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
Esempio n. 2
0
    def _do_mct_aes_test(self, file_name):
        test_vectors = load_tests(
            ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name,
            "AES Montecarlo", {"count": lambda x: int(x)})
        assert (test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                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
Esempio n. 3
0
    def _do_kat_aes_test(self, file_name, segment_size):
        test_vectors = load_tests(
            ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name,
            "AES CFB%d KAT" % segment_size, {"count": lambda x: int(x)})
        assert (test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                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
Esempio n. 4
0
def get_tests(config={}):
    from Crypto.Hash import SHA1
    from common import make_hash_tests

    tests = []

    test_vectors = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA1"),
                                "SHA1ShortMsg.rsp",
                                "KAT SHA-1",
                                { "len" : lambda x: int(x) } )

    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
Esempio n. 5
0
def get_tests(config={}):
    from Crypto.Hash import SHA1
    from .common import make_hash_tests

    tests = []

    test_vectors = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA1"),
                                "SHA1ShortMsg.rsp",
                                "KAT SHA-1",
                                { "len" : lambda x: int(x) } )

    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
Esempio n. 6
0
    def _do_tdes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"),
                                  file_name,
                                  "TDES CBC KAT",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                direction = tv
                continue

            self.description = tv.desc
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, self.des_mode, tv.iv)
            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, self.des3_mode, tv.iv)

            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
Esempio n. 7
0
    def _do_mct_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES Montecarlo",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                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
Esempio n. 8
0
    def _do_mct_aes_test(self, file_name, segment_size):
        test_vectors = load_tests(
            ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name,
            "AES CFB%d Montecarlo" % segment_size, {"count": lambda x: int(x)})
        assert (test_vectors)
        assert (segment_size in (8, 128))

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                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
Esempio n. 9
0
    def _do_mct_aes_test(self, file_name, segment_size):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES CFB%d Montecarlo" % segment_size,
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)
        assert(segment_size in (8, 128))

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                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
Esempio n. 10
0
def get_tests(config={}):
    from .common import make_hash_tests

    tests = []

    test_vectors = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA3"),
                                "ShortMsgKAT_SHA3-384.txt",
                                "KAT SHA-3 384",
                                { "len" : lambda x: int(x) } )

    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_384", test_data,
                             digest_size=SHA3.digest_size,
                             oid="2.16.840.1.101.3.4.2.9")
    tests += list_test_cases(APITest)
    return tests
Esempio n. 11
0
def get_tests(config={}):
    from .common import make_hash_tests

    tests = []

    test_vectors = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA3"),
                                "ShortMsgKAT_SHA3-384.txt",
                                "KAT SHA-3 384",
                                { "len" : lambda x: int(x) } )

    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_384", test_data,
                             digest_size=SHA3.digest_size,
                             oid="2.16.840.1.101.3.4.2.9")
    tests += list_test_cases(APITest)
    return tests
def get_tests_SHA512():
    test_vectors = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA2"),
                              "SHA512ShortMsg.rsp",
                              "KAT SHA-512",
                              {"len": lambda x: int(x)})

    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_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA2"),
                              "SHA512_224ShortMsg.rsp",
                              "KAT SHA-512/224",
                              {"len": lambda x: int(x)})

    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
Esempio n. 14
0
    def _do_kat_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES KAT",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                direction = tv
                continue

            self.description = tv.desc

            cipher = AES.new(tv.key, self.aes_mode, tv.iv)
            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
Esempio n. 15
0
    def _do_kat_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES KAT",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        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]":
                self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
            elif direction == "[DECRYPT]":
                self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
            else:
                assert False
Esempio n. 16
0
    def _do_kat_aes_test(self, file_name, segment_size):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES CFB%d KAT" % segment_size,
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        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
        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).publickey()
        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_tests(
    ("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-PSS"),
    "SigVerPSS_186-3.rsp", "Signature Verification 186-3", {
        'shaalg': lambda x: x,
        'result': lambda x: x
    })

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)
Esempio n. 18
0
     'a826fd8ce53b855fcce21c8112256fe668d5c05dd9b6b900',
     '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_tests(
        ("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"), tdes_file,
        "TDES ECB (%s)" % tdes_file, {"count": lambda x: int(x)})
    assert (test_vectors)
    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)

Esempio n. 19
0
        cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
        ct2, digest2 = cipher.encrypt_and_digest(pt)

        self.assertEqual(ct, ct2)
        self.assertEqual(digest, digest2)


from Crypto.SelfTest.loader import load_tests


class NISTTestVectorsGCM(unittest.TestCase):
    pass

test_vectors_nist = load_tests(
                        ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                        "gcmDecrypt128.rsp",
                        "GCM decrypt",
                        { "count" : lambda x: int(x) })

test_vectors_nist += load_tests(
                        ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                        "gcmEncryptExtIV128.rsp",
                        "GCM encrypt",
                        { "count" : lambda x: int(x) })

for idx, tv in enumerate(test_vectors_nist):

    # The test vector file contains some directive lines
    if isinstance(tv, str):
        continue
Esempio n. 20
0
        h = keccak.new(digest_bits=512, data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)


class KeccakVectors(unittest.TestCase):
    pass

    # TODO: add ExtremelyLong tests


test_vectors_224 =  load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "keccak"),
                                "ShortMsgKAT_224.txt",
                                "Short Messages KAT 224",
                                { "len" : lambda x: int(x) } )

test_vectors_224 += load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "keccak"),
                                "LongMsgKAT_224.txt",
                                "Long Messages KAT 224",
                                { "len" : lambda x: int(x) } )

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)
Esempio n. 21
0
        pointR = self.pointS * d + self.pointT * e
        self.assertEqual(pointR.x, pointRx)
        self.assertEqual(pointR.y, pointRy)


class TestEccPoint_PAI(unittest.TestCase):
    """Test vectors from http://point-at-infinity.org/ecc/nisttv"""

    pointG = EccPoint(_curve.Gx, _curve.Gy)


tv_pai = load_tests(("Crypto", "SelfTest", "PublicKey", "test_vectors", "ECC"),
                    "point-at-infinity.org-P256.txt",
                    "P-256 tests from point-at-infinity.org", {
                        "k": lambda k: int(k),
                        "x": lambda x: int(x, 16),
                        "y": lambda y: int(y, 16)
                    })
assert (tv_pai)
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, "test_%d" % tv.count, new_test)


class TestEccKey(unittest.TestCase):
Esempio n. 22
0

class SHAKE128Test(SHAKETest):
    shake = SHAKE128


class SHAKE256Test(SHAKETest):
    shake = SHAKE256


class SHAKEVectors(unittest.TestCase):
    pass


test_vectors_128 = load_tests(
    ("Crypto", "SelfTest", "Hash", "test_vectors", "SHA3"),
    "ShortMsgKAT_SHAKE128.txt", "Short Messages KAT SHAKE128",
    {"len": lambda x: int(x)})

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)
Esempio n. 23
0
        pointRy = 0xf2504055c03cede12d22720dad69c745106b6607ec7e50dd35d54bd80f615275

        pointR = self.pointS * d + self.pointT * e
        self.assertEqual(pointR.x, pointRx)
        self.assertEqual(pointR.y, pointRy)


class TestEccPoint_PAI(unittest.TestCase):
    """Test vectors from http://point-at-infinity.org/ecc/nisttv"""

    pointG = EccPoint(_curve.Gx, _curve.Gy)


tv_pai = load_tests(("Crypto", "SelfTest", "PublicKey", "test_vectors", "ECC"),
                    "point-at-infinity.org-P256.txt",
                    "P-256 tests from point-at-infinity.org",
                    { "k" : lambda k: int(k),
                      "x" : lambda x: int(x, 16),
                      "y" : lambda y: int(y, 16)} )
assert(tv_pai)
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, "test_%d" % tv.count, new_test)


class TestEccKey(unittest.TestCase):

    def test_private_key(self):
Esempio n. 24
0
        cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
        ct2, digest2 = cipher.encrypt_and_digest(pt)

        self.assertEqual(ct, ct2)
        self.assertEqual(digest, digest2)


from Crypto.SelfTest.loader import load_tests


class NISTTestVectorsGCM(unittest.TestCase):
    pass

test_vectors_nist = load_tests(
                        ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                        "gcmDecrypt128.rsp",
                        "GCM decrypt",
                        { "count" : lambda x: int(x) })

test_vectors_nist += load_tests(
                        ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                        "gcmEncryptExtIV128.rsp",
                        "GCM encrypt",
                        { "count" : lambda x: int(x) })

for idx, tv in enumerate(test_vectors_nist):

    # The test vector file contains some directive lines
    if isinstance(tv, basestring):
        continue
Esempio n. 25
0
        """Verify public/private method"""

        self.description = "can_sign() test"
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertTrue(signer.can_sign())

        signer = DSS.new(self.key_pub, 'fips-186-3')
        self.assertFalse(signer.can_sign())


class FIPS_DSA_Tests_KAT(unittest.TestCase):
    pass


test_vectors_verify = load_tests(
    ("Crypto", "SelfTest", "Signature", "test_vectors", "DSA"),
    "FIPS_186_3_SigVer.rsp", "Signature Verification 186-3",
    {'result': lambda x: x})

for idx, tv in enumerate(test_vectors_verify):

    if isinstance(tv, str):
        res = re.match("\[mod = L=([0-9]+), N=([0-9]+), ([a-zA-Z0-9-]+)\]", tv)
        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
        suborder = tv.q
        continue
Esempio n. 26
0
        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_tests(
    ("Crypto", "SelfTest", "Hash", "test_vectors", "keccak"),
    "ShortMsgKAT_224.txt", "Short Messages KAT 224", {"len": lambda x: int(x)})

test_vectors_224 += load_tests(
    ("Crypto", "SelfTest", "Hash", "test_vectors", "keccak"),
    "LongMsgKAT_224.txt", "Long Messages KAT 224", {"len": lambda x: int(x)})

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)
Esempio n. 27
0
        signature = bchr(7) + signature[1:]
        self.assertRaises(ValueError, signer.verify, hash_obj, signature)

    def test_sign_verify(self):
        """Verify public/private method"""

        self.description = "can_sign() test"
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertTrue(signer.can_sign())

        signer = DSS.new(self.key_pub, 'fips-186-3')
        self.assertFalse(signer.can_sign())


test_vectors_verify = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "DSA"),
                                 "FIPS_186_3_SigVer.rsp",
                                 "Signature Verification 186-3",
                                 {'result' : lambda x: x})

for idx, tv in enumerate(test_vectors_verify):

    if isinstance(tv, str):
        res = re.match("\[mod = L=([0-9]+), N=([0-9]+), ([a-zA-Z0-9-]+)\]", tv)
        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
        suborder = tv.q
        continue
Esempio n. 28
0

class FIPS_PKCS1_Verify_Tests(unittest.TestCase):

    def shortDescription(self):
        return "FIPS PKCS1 Tests (Verify)"

    def test_can_sign(self):
        test_public_key = RSA.generate(1024).publickey()
        verifier = pkcs1_15.new(test_public_key)
        self.assertEqual(verifier.can_sign(), False)


test_vectors_verify = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-v1.5"),
                                 "SigVer15_186-3.rsp",
                                 "Signature Verification 186-3",
                                 { 'shaalg' : lambda x: x,
                                   'd' : lambda x: int(x),
                                   'result' : lambda x: x })


for count, tv in enumerate(test_vectors_verify):
    if isinstance(tv, basestring):
        continue
    if hasattr(tv, "n"):
        modulus = tv.n
        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) for x in modulus, tv.e])
    verifier = pkcs1_15.new(public_key)
Esempio n. 29
0

class SHAKE128Test(SHAKETest):
        shake = SHAKE128


class SHAKE256Test(SHAKETest):
        shake = SHAKE256


class SHAKEVectors(unittest.TestCase):
    pass


test_vectors_128 = load_tests(("Crypto", "SelfTest", "Hash", "test_vectors", "SHA3"),
                               "ShortMsgKAT_SHAKE128.txt",
                               "Short Messages KAT SHAKE128",
                               { "len" : lambda x: int(x) } )

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)
Esempio n. 30
0
        '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_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"),
                                  tdes_file,
                                  "TDES ECB (%s)" % tdes_file,
                                  { "count" : lambda x: int(x) } )
    assert(test_vectors)
    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)