def setUp(self):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "rsa_signature_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#2
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            try:
                key = ECC.import_key(group['keyPem'])
            except ValueError:
                continue

            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "ECDSAVer"

            from collections import namedtuple
            TestVector = namedtuple(
                'TestVector',
                'id comment msg sig key hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(test['tcId'], test['comment'],
                                unhexlify(test['msg']), unhexlify(test['sig']),
                                key, hash_module, test['result'] != "invalid",
                                test['result'] == "acceptable")
                self.tv.append(tv)
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            key = RSA.import_key(group['keyPem'])
            hash_module = get_hash_module(group['sha'])
            sLen = group['sLen']

            assert group['type'] == "RsassaPssVerify"
            assert group['mgf'] == "MGF1"

            mgf1_hash = get_hash_module(group['mgfSha'])

            def mgf(x, y, mh=mgf1_hash):
                return MGF1(x, y, mh)

            from collections import namedtuple
            TestVector = namedtuple(
                'TestVector',
                'id comment msg sig key mgf sLen hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(test['tcId'], test['comment'],
                                unhexlify(test['msg']), unhexlify(test['sig']),
                                key, mgf, sLen, hash_module,
                                test['result'] != "invalid",
                                test['result'] == "acceptable")
                self.tv.append(tv)
示例#4
0
    def setUp(self):

        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            self.name.lower() + "-test.txt")

        expected = "in"
        self.test_vectors = []
        for line_number, line in enumerate(open(test_vector_file, "rt")):

            if line.strip() == "" or line.startswith("#"):
                continue

            res = re.match("%s:\t([0-9A-Fa-f]*)" % expected, line)
            if not res:
                raise ValueError("Incorrect test vector format (line %d)"
                                 % line_number)

            if res.group(1):
                bin_value = unhexlify(tobytes(res.group(1)))
            else:
                bin_value = b("")
            if expected == "in":
                input_data = bin_value
                expected = "key"
            elif expected == "key":
                key = bin_value
                expected = "hash"
            else:
                result = bin_value
                expected = "in"
                self.test_vectors.append((input_data, key, result))
示例#5
0
    def setUp(self):
        file_in = open(
            pycryptodome_filename(
                "Crypto.SelfTest.Hash.test_vectors.wycheproof".split("."),
                "aes_cmac_test.json"), "rt")
        tv_tree = json.load(file_in)

        class TestVector(object):
            pass

        self.tv = []

        for group in tv_tree['testGroups']:
            tag_size = group['tagSize'] // 8
            for test in group['tests']:
                tv = TestVector()
                tv.tag_size = tag_size

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'key', 'msg', 'tag':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#6
0
    def setUp(self):
        file_in = open(pycryptodome_filename(
                        "Crypto.SelfTest.Signature.test_vectors.wycheproof".split("."),
                        "rsa_signature_test.json"), "rt")
        tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#7
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            try:
                key = ECC.import_key(group['keyPem'])
            except ValueError:
                continue

            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "ECDSAVer"

            for test in group['tests']:
                tv = TestVector()

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#8
0
    def setUp(self):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "dsa_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        self.tv = []

        for group in tv_tree['testGroups']:
            key = DSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "DSAVer"
            
            from collections import namedtuple
            TestVector = namedtuple('TestVector', 'id comment msg sig key hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(
                    test['tcId'],
                    test['comment'],
                    unhexlify(test['msg']),
                    unhexlify(test['sig']),
                    key,
                    hash_module,
                    test['result'] != "invalid",
                    test['result'] == "acceptable"
                )
                self.tv.append(tv)
示例#9
0
    def load_tests(self, filename):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        result = []

        for group in tv_tree['testGroups']:
            tag_size = group['tagSize'] // 8
            for test in group['tests']:
                tv = TestVector()
                tv.tag_size = tag_size

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                tv.algo = tv_tree['algorithm']

                result.append(tv)
        return result
示例#10
0
    def load_tests(self, filename):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        result = []

        for group in tv_tree['testGroups']:

            rsa_key = RSA.import_key(group['privateKeyPem'])
        
            for test in group['tests']:
                tv = TestVector()

                tv.rsa_key = rsa_key

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'ct':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"

                result.append(tv)
        return result
示例#11
0
def load_file(filename, mode="rb"):
    fd = open(pycryptodome_filename([
                                    "Crypto",
                                    "SelfTest",
                                    "PublicKey",
                                    "test_vectors",
                                    "ECC",
                                    ], filename), mode)
    return fd.read()
示例#12
0
def load_file(filename, mode="rb"):
    fd = open(pycryptodome_filename([
                                    "Crypto",
                                    "SelfTest",
                                    "PublicKey",
                                    "test_vectors",
                                    "ECC",
                                    ], filename), mode)
    return fd.read()
示例#13
0
    def load_tests(self, filename):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass

        result = []

        for group in tv_tree['testGroups']:

            rsa_key = RSA.import_key(group['privateKeyPem'])
            if group['sha'] == "SHA-1":
                hash_mod = SHA1
            elif group['sha'] == "SHA-224":
                hash_mod = SHA224
            elif group['sha'] == "SHA-256":
                hash_mod = SHA256
            elif group['sha'] == "SHA-384":
                hash_mod = SHA384
            elif group['sha'] == "SHA-512":
                hash_mod = SHA512
            else:
                raise ValueError("Unknown sha " + group['sha'])

            if group['mgfSha'] == "SHA-1":
                mgf = lambda x, y: MGF1(x, y, SHA1)
            elif group['mgfSha'] == "SHA-224":
                mgf = lambda x, y: MGF1(x, y, SHA224)
            elif group['mgfSha'] == "SHA-256":
                mgf = lambda x, y: MGF1(x, y, SHA256)
            elif group['mgfSha'] == "SHA-384":
                mgf = lambda x, y: MGF1(x, y, SHA384)
            elif group['mgfSha'] == "SHA-512":
                mgf = lambda x, y: MGF1(x, y, SHA512)
            else:
                raise ValueError("Unknown mgf/sha " + group['mgfSha'])

            for test in group['tests']:
                tv = TestVector()

                tv.rsa_key = rsa_key
                tv.hash_mod = hash_mod
                tv.mgf = mgf
                tv.algo = "%s with MGF1/%s" % (group['sha'], group['mgfSha'])

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'ct', 'label':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"

                result.append(tv)
        return result
示例#14
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass

        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])

            hash_name = group['sha']
            if hash_name == "SHA-512":
                hash_module = SHA512
            elif hash_name == "SHA-512/224":
                hash_module = SHA512.new(truncate="224")
            elif hash_name == "SHA-512/256":
                hash_module = SHA512.new(truncate="256")
            elif hash_name == "SHA3-512":
                hash_module = SHA3_512
            elif hash_name == "SHA-384":
                hash_module = SHA384
            elif hash_name == "SHA3-384":
                hash_module = SHA3_384
            elif hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA3-256":
                hash_module = SHA3_256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA3-224":
                hash_module = SHA3_224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                raise ValueError("Unknown hash algorithm: " + hash_name)

            type_name = group['type']
            if type_name not in ("RsassaPkcs1Verify", "RsassaPkcs1Generate"):
                raise ValueError("Unknown type name " + type_name)

            for test in group['tests']:
                tv = TestVector()

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#15
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            try:
                key = ECC.import_key(group['keyPem'])
            except ValueError:
                continue

            hash_name = group['sha']
            if hash_name == "SHA-512":
                hash_module = SHA512
            elif hash_name == "SHA3-512":
                hash_module = SHA3_512
            elif hash_name == "SHA-384":
                hash_module = SHA384
            elif hash_name == "SHA3-384":
                hash_module = SHA3_384
            elif hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA3-256":
                hash_module = SHA3_256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                raise ValueError("Unknown hash type " + hash_name)

            encoding_name = group['type']
            if encoding_name == "EcdsaVerify":
                encoding = "der"
            elif encoding_name == "EcdsaP1363Verify":
                encoding = "binary"
            else:
                raise ValueError("Unknown signature type " + encoding_name)

            from collections import namedtuple
            TestVector = namedtuple(
                'TestVector',
                'id comment msg encoding sig key hash_module valid warning filename'
            )

            for test in group['tests']:
                tv = TestVector(test['tcId'], test['comment'],
                                unhexlify(test['msg']), encoding,
                                unhexlify(test['sig']), key, hash_module,
                                test['result'] != "invalid",
                                test['result'] == "acceptable", filename)
                self.tv.append(tv)
def load_tests(dir_comps, file_name, description, conversions):
    """Load and parse a test vector file

    This function returnis a list of objects, one per group of adjacent
    KV lines or for a single line in the form "[.*]".

    For a group of lines, the object has one attribute per line.
    """

    description = "%s test (%s)" % (description, file_name)

    with open(pycryptodome_filename(dir_comps, file_name)) as file_in:
        results = _load_tests(dir_comps, file_in, description, conversions)
    return results
示例#17
0
    def setUp(self):
        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            "tv1.txt")

        self.test_vectors = []
        for line_number, line in enumerate(open(test_vector_file, "rt")):
            if line.strip() == "" or line.startswith("#"):
                continue
            res = re.match("digest: ([0-9A-Fa-f]*)", line)
            if not res:
                raise ValueError("Incorrect test vector format (line %d)"
                                 % line_number)

            self.test_vectors.append(unhexlify(tobytes(res.group(1))))
示例#18
0
    def setUp(self):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "aes_siv_cmac_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            for test in group['tests']:
                tv = TestVector()

                tv.id = test['tcId']
                for attr in 'key', 'aad', 'msg', 'ct':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                self.tv.append(tv)
示例#19
0
    def setUp(self):
        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            "tv2.txt")

        self.test_vectors = []
        with open(test_vector_file, "rt") as test_vector_fd:
            for line_number, line in enumerate(test_vector_fd):
                if line.strip() == "" or line.startswith("#"):
                    continue
                res = re.match(r"digest\(([0-9]+)\): ([0-9A-Fa-f]*)", line)
                if not res:
                    raise ValueError("Incorrect test vector format (line %d)"
                                     % line_number)

                key_size = int(res.group(1))
                result = unhexlify(tobytes(res.group(2)))
                self.test_vectors.append((key_size, result))
示例#20
0
def load_pycryptodome_raw_lib(name, cdecl):
    """Load a shared library and return a handle to it.

    @name,  the name of the library expressed as a PyCryptodome module,
            for instance Crypto.Cipher._raw_cbc.

    @cdecl, the C function declarations.
    """

    split = name.split(".")
    dir_comps, basename = split[:-1], split[-1]
    for ext in extension_suffixes:
        try:
            return load_lib(pycryptodome_filename(dir_comps, basename + ext),
                            cdecl)
        except OSError:
            pass
    raise OSError("Cannot load native module '%s'" % name)
    def setUp(self):
        test_vector_file = pycryptodome_filename(
            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
            "tv2.txt")

        self.test_vectors = []
        with open(test_vector_file, "rt") as test_vector_fd:
            for line_number, line in enumerate(test_vector_fd):
                if line.strip() == "" or line.startswith("#"):
                    continue
                res = re.match(r"digest\(([0-9]+)\): ([0-9A-Fa-f]*)", line)
                if not res:
                    raise ValueError("Incorrect test vector format (line %d)" %
                                     line_number)

                key_size = int(res.group(1))
                result = unhexlify(tobytes(res.group(2)))
                self.test_vectors.append((key_size, result))
    def setUp(self):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "aes_siv_cmac_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            for test in group['tests']:
                tv = TestVector()

                tv.id = test['tcId']
                for attr in 'key', 'aad', 'msg', 'ct':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                self.tv.append(tv)
示例#23
0
def load_pycryptodome_raw_lib(name, cdecl):
    """Load a shared library and return a handle to it.

    @name,  the name of the library expressed as a PyCryptodome module,
            for instance Crypto.Cipher._raw_cbc.

    @cdecl, the C function declarations.
    """

    split = name.split(".")
    dir_comps, basename = split[:-1], split[-1]
    attempts = []
    for ext in extension_suffixes:
        try:
            filename = basename + ext
            return load_lib(pycryptodome_filename(dir_comps, filename), cdecl)
        except OSError, exp:
            attempts.append("Trying '%s': %s" % (filename, str(exp)))
示例#24
0
def load_pycryptodome_raw_lib(name, cdecl):
    """Load a shared library and return a handle to it.

    @name,  the name of the library expressed as a PyCryptodome module,
            for instance Crypto.Cipher._raw_cbc.

    @cdecl, the C function declarations.
    """

    split = name.split(".")
    dir_comps, basename = split[:-1], split[-1]
    for ext, mod, typ in imp.get_suffixes():
        if typ == imp.C_EXTENSION:
            try:
                return load_lib(pycryptodome_filename(dir_comps, basename + ext), cdecl)
            except OSError:
                pass
    raise OSError("Cannot load native module '%s'" % name)
def load_pycryptodome_raw_lib(name, cdecl):
    """Load a shared library and return a handle to it.

    @name,  the name of the library expressed as a PyCryptodome module,
            for instance Crypto.Cipher._raw_cbc.

    @cdecl, the C function declarations.
    """

    split = name.split(".")
    dir_comps, basename = split[:-1], split[-1]
    attempts = []
    for ext in extension_suffixes:
        try:
            filename = basename + ext
            return load_lib(pycryptodome_filename(dir_comps, filename),
                            cdecl)
        except OSError as exp:
            attempts.append("Trying '%s': %s" % (filename, str(exp)))
    raise OSError("Cannot load native module '%s': %s" % (name, ", ".join(attempts)))
示例#26
0
    def setUp(self):
        comps = "Crypto.SelfTest.Hash.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "aes_cmac_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            tag_size = group['tagSize'] // 8
            for test in group['tests']:
                tv = TestVector()
                tv.tag_size = tag_size

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'key', 'msg', 'tag':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#27
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-512":
                hash_module = SHA512
            elif hash_name == "SHA-384":
                hash_module = SHA384
            elif hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                raise ValueError("Unknown hash algorithm: " + hash_name)
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
示例#28
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Protocol.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        algo_name = tv_tree['algorithm']
        if algo_name == "HKDF-SHA-1":
            hash_module = SHA1
        elif algo_name == "HKDF-SHA-256":
            hash_module = SHA256
        elif algo_name == "HKDF-SHA-384":
            hash_module = SHA384
        elif algo_name == "HKDF-SHA-512":
            hash_module = SHA512
        else:
            raise ValueError("Unknown algorithm " + algo_name)

        for group in tv_tree['testGroups']:

            from collections import namedtuple
            TestVector = namedtuple('TestVector',
                                    'id comment ikm salt info size okm hash_module valid warning filename')

            for test in group['tests']:
                tv = TestVector(
                    test['tcId'],
                    test['comment'],
                    unhexlify(test['ikm']),
                    unhexlify(test['salt']),
                    unhexlify(test['info']),
                    int(test['size']),
                    unhexlify(test['okm']),
                    hash_module,
                    test['result'] != "invalid",
                    test['result'] == "acceptable",
                    filename
                )
                self.tv.append(tv)
示例#29
0
def load_pycryptodome_raw_lib(name, cdecl):
    """Load a shared library and return a handle to it.

    @name,  the name of the library expressed as a PyCryptodome module,
            for instance Crypto.Cipher._raw_cbc.

    @cdecl, the C function declarations.
    """

    split = name.split(".")
    dir_comps, basename = split[:-1], split[-1]
    attempts = []
    for ext in extension_suffixes:
        try:
            filename = basename + ext
            full_name = pycryptodome_filename(dir_comps, filename)
            if not os.path.isfile(full_name):
                attempts.append("Not found '%s'" % filename)
                continue
            return load_lib(full_name, cdecl)
        except OSError as exp:
            attempts.append("Cannot load '%s': %s" % (filename, str(exp)))
    raise OSError("Cannot load native module '%s': %s" %
                  (name, ", ".join(attempts)))
示例#30
0
def load_tests(dir_comps, file_name, description, conversions):
    """Load and parse a test vector file

    This function returnis a list of objects, one per group of adjacent
    KV lines or for a single line in the form "[.*]".

    For a group of lines, the object has one attribute per line.
    """

    file_in = open(pycryptodome_filename(dir_comps, file_name))
    description = "%s test (%s)" % (description, file_name)

    line_number = 0
    results = []

    class TestVector(object):
        def __init__(self, description, count):
            self.desc = description
            self.count = count
            self.others = []

    test_vector = None
    count = 0
    new_group = True

    while True:
        line_number += 1
        line = file_in.readline()
        if not line:
            if test_vector is not None:
                results.append(test_vector)
            break
        line = line.strip()

        # Skip comments and empty lines
        if line.startswith('#') or not line:
            new_group = True
            continue

        if line.startswith("["):
            if test_vector is not None:
                results.append(test_vector)
            test_vector = None
            results.append(line)
            continue

        if new_group:
            count += 1
            new_group = False
            if test_vector is not None:
                results.append(test_vector)
            test_vector = TestVector("%s (#%d)" % (description, count), count)

        res = re.match("([A-Za-z0-9]+) = ?(.*)", line)
        if not res:
            test_vector.others += [line]
        else:
            token = res.group(1).lower()
            data = res.group(2).lower()

            conversion = conversions.get(token, None)
            if conversion is None:
                if len(data) % 2 != 0:
                    data = "0" + data
                setattr(test_vector, token, unhexlify(data))
            else:
                setattr(test_vector, token, conversion(data))

        # This line is ignored
    return results
def load_file(filename, mode="rb"):
    comps = ["Crypto", "SelfTest", "PublicKey", "test_vectors", "ECC"]
    with open(pycryptodome_filename(comps, filename), mode) as fd:
        return fd.read()
示例#32
0
def load_file(filename, mode="rb"):
    comps = [ "Crypto", "SelfTest", "PublicKey", "test_vectors", "ECC" ]
    with open(pycryptodome_filename(comps, filename), mode) as fd:
        return fd.read()
示例#33
0
    gmp_defs = "typedef unsigned long UNIX_ULONG;" + gmp_defs_common
    lib = load_lib("gmp", gmp_defs)
    implementation = {"library": "gmp", "api": backend}
except OSError:
    import platform
    bits, linkage = platform.architecture()
    if bits.startswith("64") and linkage.startswith("Win"):
        # MPIR uses unsigned long long where GMP uses unsigned long
        # (LLP64 vs LP64)
        gmp_defs = "typedef unsigned long long UNIX_ULONG;" + gmp_defs_common
        c_ulong = c_ulonglong
    # Try to load private MPIR lib first (wheel)
    try:
        from Crypto.Util._file_system import pycryptodome_filename

        mpir_dll = pycryptodome_filename(("Crypto", "Math"), "mpir.dll")
        lib = load_lib(mpir_dll, gmp_defs)
    except OSError:
        lib = load_lib("mpir", gmp_defs)

    implementation = {"library": "mpir", "api": backend}

# In order to create a function that returns a pointer to
# a new MPZ structure, we need to break the abstraction
# and know exactly what ffi backend we have
if implementation["api"] == "ctypes":
    from ctypes import Structure, c_int, c_void_p, byref

    class _MPZ(Structure):
        _fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int),
                    ('_mp_d', c_void_p)]
示例#34
0
    gmp_defs = "typedef unsigned long UNIX_ULONG;" + gmp_defs_common
    lib = load_lib("gmp", gmp_defs)
    implementation = { "library":"gmp", "api":backend }
except OSError:
    import platform
    bits, linkage = platform.architecture()
    if bits.startswith("64") and linkage.startswith("Win"):
        # MPIR uses unsigned long long where GMP uses unsigned long
        # (LLP64 vs LP64)
        gmp_defs = "typedef unsigned long long UNIX_ULONG;" + gmp_defs_common
        c_ulong = c_ulonglong
    # Try to load private MPIR lib first (wheel)
    try:
        from Crypto.Util._file_system import pycryptodome_filename

        mpir_dll = pycryptodome_filename(("Crypto", "Math"), "mpir.dll")
        lib = load_lib(mpir_dll, gmp_defs)
    except OSError:
        lib = load_lib("mpir", gmp_defs)

    implementation = { "library":"mpir", "api":backend }

# In order to create a function that returns a pointer to
# a new MPZ structure, we need to break the abstraction
# and know exactly what ffi backend we have
if implementation["api"] == "ctypes":
    from ctypes import Structure, c_int, c_void_p, byref

    class _MPZ(Structure):
        _fields_ = [('_mp_alloc', c_int),
                    ('_mp_size', c_int),