Exemplo n.º 1
0
    def test_export_openssh_compressed(self):
        key_file = load_file("ecc_p256_public_openssh.txt", "rt")
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="OpenSSH", compress=True)
        assert len(key_file) > len(key_file_compressed)
        self.assertEqual(pub_key, ECC.import_key(key_file_compressed))
Exemplo n.º 2
0
    def test_import_openssh_private_clear(self):
        key_file = load_file("ecc_p521_private_openssh.pem")
        key_file_old = load_file("ecc_p521_private_openssh_old.pem")

        key = ECC.import_key(key_file)
        key_old = ECC.import_key(key_file_old)
        self.assertEqual(key, key_old)
Exemplo n.º 3
0
    def test_import_openssh_private_password(self):
        key_file = load_file("ecc_p521_private_openssh_pwd.pem")
        key_file_old = load_file("ecc_p521_private_openssh_pwd_old.pem")

        key = ECC.import_key(key_file, b"password")
        key_old = ECC.import_key(key_file_old)
        self.assertEqual(key, key_old)
Exemplo n.º 4
0
    def test_compressed_curve(self):

        # Compressed P-384 curve (Y-point is even)
        # openssl ecparam -name secp384p1 -genkey -noout -conv_form compressed -out /tmp/a.pem
        # openssl ec -in /tmp/a.pem -text -noout
        pem1 = """-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDAM0lEIhvXuekK2SWtdbgOcZtBaxa9TxfpO/GcDFZLCJ3JVXaTgwken
QT+C+XLtD6WgBwYFK4EEACKhZANiAATs0kZMhFDu8DoBC21jrSDPyAUn4aXZ/DM4
ylhDfWmb4LEbeszXceIzfhIUaaGs5y1xXaqf5KXTiAAYx2pKUzAAM9lcGUHCGKJG
k4AgUmVJON29XoUilcFrzjDmuye3B6Q=
-----END EC PRIVATE KEY-----"""

        # Compressed P-384 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDDHPFTslYLltE16fHdSDTtE/2HTmd3M8mqy5MttAm4wZ833KXiGS9oe
kFdx9sNV0KygBwYFK4EEACKhZANiAASLIE5RqVMtNhtBH/u/p/ifqOAlKnK/+RrQ
YC46ZRsnKNayw3wATdPjgja7L/DSII3nZK0G6KOOVwJBznT/e+zudUJYhZKaBLRx
/bgXyxUtYClOXxb1Y/5N7txLstYRyP0=
-----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0x07a4)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0xc8fd)
Exemplo n.º 5
0
    def test_compressed_curve(self):

        # Compressed P-521 curve (Y-point is even)
        # openssl ecparam -name secp521r1 -genkey -noout -conv_form compressed -out /tmp/a.pem
        # openssl ec -in /tmp/a.pem -text -noout
        pem1 = """-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIAnm1CEjVjvNfXEN730p+D6su5l+mOztdc5XmTEoti+s2R4GQ4mAv3
0zYLvyklvOHw0+yy8d0cyGEJGb8T3ZVKmg2gBwYFK4EEACOhgYkDgYYABAHzjTI1
ckxQ3Togi0LAxiG0PucdBBBs5oIy3df95xv6SInp70z+4qQ2EltEmdNMssH8eOrl
M5CYdZ6nbcHMVaJUvQEzTrYxvFjOgJiOd+E9eBWbLkbMNqsh1UKVO6HbMbW0ohCI
uGxO8tM6r3w89/qzpG2SvFM/fvv3mIR30wSZDD84qA==
-----END EC PRIVATE KEY-----"""

        # Compressed P-521 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIB84OfhJluLBRLn3+cC/RQ37C2SfQVP/t0gQK2tCsTf5avRcWYRrOJ
PmX9lNnkC0Hobd75QFRmdxrB0Wd1/M4jZOWgBwYFK4EEACOhgYkDgYYABAAMZcdJ
1YLCGHt3bHCEzdidVy6+brlJIbv1aQ9fPQLF7WKNv4c8w3H8d5a2+SDZilBOsk5c
6cNJDMz2ExWQvxl4CwDJtJGt1+LHVKFGy73NANqVxMbRu+2F8lOxkNp/ziFTbVyV
vv6oYkMIIi7r5oQWAiQDrR2mlrrFDL9V7GH/r8SWQw==
-----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0x38a8)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0x9643)
Exemplo n.º 6
0
    def test_export_openssh_compressed(self):
        key_file = load_file("ecc_p256_public_openssh.txt", "rt")
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="OpenSSH", compress=True)
        assert len(key_file) > len(key_file_compressed)
        self.assertEquals(pub_key, ECC.import_key(key_file_compressed))
    def test_import_private_pkcs8_clear(self):
        key_file = load_file("ecc_p256_private_p8_clear.der")

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_private, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_private, key)
    def test_import_private_pkcs8_encrypted_1(self):
        key_file = load_file("ecc_p256_private_p8.der")

        key = ECC._import_der(key_file, "secret")
        self.assertEqual(ref_private, key)

        key = ECC.import_key(key_file, "secret")
        self.assertEqual(ref_private, key)
    def test_import_x509_der(self):
        key_file = load_file("ecc_p256_x509.der")

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
    def test_import_openssh(self):
        key_file = load_file("ecc_p256_public_openssh.txt")

        key = ECC._import_openssh(key_file)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
Exemplo n.º 11
0
    def test_import_private_pkcs8_clear(self):
        key_file = load_file("ecc_p256_private_p8_clear.der")

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_private, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_private, key)
Exemplo n.º 12
0
    def test_import_private_pkcs8_encrypted_1(self):
        key_file = load_file("ecc_p256_private_p8.der")

        key = ECC._import_der(key_file, "secret")
        self.assertEqual(ref_private, key)

        key = ECC.import_key(key_file, "secret")
        self.assertEqual(ref_private, key)
Exemplo n.º 13
0
    def test_import_x509_der(self):
        key_file = load_file("ecc_p256_x509.der")

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
Exemplo n.º 14
0
    def test_import_openssh(self):
        key_file = load_file("ecc_p256_public_openssh.txt")

        key = ECC._import_openssh(key_file)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
    def test_import_private_pem_encrypted(self):
        for algo in "des3", : # TODO: , "aes128", "aes192", "aes256_gcm":
            key_file = load_file("ecc_p256_private_enc_%s.pem" % algo)

            key = ECC.import_key(key_file, "secret")
            self.assertEqual(ref_private, key)

            key = ECC.import_key(tostr(key_file), b("secret"))
            self.assertEqual(ref_private, key)
Exemplo n.º 16
0
    def test_generate(self):

        key = ECC.generate(curve="P-256")
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(_curve.Gx, _curve.Gy) * key.d)

        # Other names
        ECC.generate(curve="secp256r1")
        ECC.generate(curve="prime256v1")
Exemplo n.º 17
0
    def test_import_private_pem_encrypted(self):
        for algo in "des3", :  # TODO: , "aes128", "aes192", "aes256_gcm":
            key_file = load_file("ecc_p256_private_enc_%s.pem" % algo)

            key = ECC.import_key(key_file, "secret")
            self.assertEqual(ref_private, key)

            key = ECC.import_key(tostr(key_file), b"secret")
            self.assertEqual(ref_private, key)
Exemplo n.º 18
0
    def test_generate(self):

        curve = _curves['p521']
        key = ECC.generate(curve="P-521")
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(curve.Gx, curve.Gy, "p521") * key.d)

        # Other names
        ECC.generate(curve="secp521r1")
        ECC.generate(curve="prime521v1")
Exemplo n.º 19
0
    def test_generate(self):

        curve = _curves['p384']
        key = ECC.generate(curve="P-384")
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(curve.Gx, curve.Gy, "p384") * key.d)

        # Other names
        ECC.generate(curve="secp384r1")
        ECC.generate(curve="prime384v1")
Exemplo n.º 20
0
def create_ref_keys():
    key_lines = load_file("ecc_p256.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:5]))
    public_key_xy = compact(key_lines[6:11])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    return (ECC.construct(curve="P-256", d=private_key_d),
            ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys():
    key_lines = load_file("ecc_p256.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:5]))
    public_key_xy = compact(key_lines[6:11])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    return (ECC.construct(curve="P-256", d=private_key_d),
            ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
Exemplo n.º 22
0
    def test_import_public_der(self):
        key_file = load_file("ecc_p256_public.der")

        key = ECC._import_subjectPublicKeyInfo(key_file)
        self.assertEqual(ref_public, key)

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
    def test_import_public_der(self):
        key_file = load_file("ecc_p256_public.der")

        key = ECC._import_subjectPublicKeyInfo(key_file)
        self.assertEqual(ref_public, key)

        key = ECC._import_der(key_file, None)
        self.assertEqual(ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
Exemplo n.º 24
0
    def test_generate(self):

        key = ECC.generate(curve="P-256")
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(_curves['p256'].Gx,
                                              _curves['p256'].Gy) * key.d,
                                              "p256")

        # Other names
        ECC.generate(curve="secp256r1")
        ECC.generate(curve="prime256v1")
Exemplo n.º 25
0
def create_ref_keys_p521():
    key_len = 66
    key_lines = load_file("ecc_p521.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:7]))
    public_key_xy = compact(key_lines[8:17])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
    public_key_y = bytes_to_long(public_key_xy[key_len+1:])

    return (ECC.construct(curve="P-521", d=private_key_d),
            ECC.construct(curve="P-521", point_x=public_key_x, point_y=public_key_y))
Exemplo n.º 26
0
    def test_import_private_der(self):
        key_file = load_file("ecc_p521_private.der")

        key = ECC._import_private_der(key_file, None)
        self.assertEqual(self.ref_private, key)

        key = ECC._import_der(key_file, None)
        self.assertEqual(self.ref_private, key)

        key = ECC.import_key(key_file)
        self.assertEqual(self.ref_private, key)
Exemplo n.º 27
0
    def test_generate(self):

        key = ECC.generate(curve="P-192")
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(_curves['p192'].Gx,
                                              _curves['p192'].Gy,
                                              "P-192") * key.d,
                                              "p192")

        # Other names
        ECC.generate(curve="secp192r1")
        ECC.generate(curve="prime192v1")
Exemplo n.º 28
0
 def get_key_type(key):
     key = bytes(key)
     try:
         RSA.import_key(key)
         return 'RSA'
     except ValueError:
         pass
     try:
         ECC.import_key(key)
         return 'ECC'
     except ValueError:
         pass
     return 'Unknown'
Exemplo n.º 29
0
    def test_unsupported_curve(self):

        # openssl ecparam -name secp224r1 -genkey -noout -out strange-curve.pem -conv_form uncompressed
        curve = """-----BEGIN EC PRIVATE KEY-----
MGgCAQEEHEi7xTHW+5oT8wgpjoEKV7uwMuY8rt2YUZe4j1SgBwYFK4EEACGhPAM6
AATJgfOG+Bnki8robpNM8MtArji43GU9up4B0x9sVhqB+fZP+hXgV9ITN7YX4E/k
gVnJp9EBND/tHQ==
-----END EC PRIVATE KEY-----"""

        from Cryptodome.PublicKey.ECC import UnsupportedEccFeature
        try:
            ECC.import_key(curve)
        except UnsupportedEccFeature, uef:
            assert ("1.3.132.0.33" in str(uef))
Exemplo n.º 30
0
async def verify_ecdsa_signature(name: FormalName, sig: SignaturePtrs) -> bool:
    global local_anchor

    sig_info = sig.signature_info
    covered_part = sig.signature_covered_part
    sig_value = sig.signature_value_buf
    if not sig_info or sig_info.signature_type != SignatureType.SHA256_WITH_ECDSA:
        return False
    if not covered_part or not sig_value:
        return False
    key_name = sig_info.key_locator.name[0:]
    logging.debug('Extract key_name: %s', Name.to_str(key_name))

    # local trust anchor pre-shared, already know server's public key
    key_bits = None
    try:
        key_bits = bytes(local_anchor.content)
    except (KeyError, AttributeError):
        logging.debug('Cannot load pub key from received certificate')
        return False
    pk = ECC.import_key(key_bits)
    verifier = DSS.new(pk, 'fips-186-3', 'der')
    sha256_hash = SHA256.new()
    for blk in covered_part:
        sha256_hash.update(blk)
    try:
        verifier.verify(sha256_hash, bytes(sig_value))
    except ValueError:
        return False
    return True
Exemplo n.º 31
0
    def load(
        cls,
        data: bytes,
        passphrase: typing.Optional[bytes] = None,
    ) -> ECCPrivateKey:
        """Loads the private key as binary object and returns the Key
        interface.

        Args:
            data (bytes):
                The key as bytes object.
            passphrase (bytes, bytearray, memoryview):
                The passphrase that deserializes the private key.
                ``passphrase`` must be a ``bytes`` object if the key
                was encrypted while serialization, otherwise ``None``.

        Returns:
            ECCPrivateKey: An ECC private key.

        Raises:
            ValueError: if the key could not be deserialized.
        """
        try:
            key = ECC.import_key(data, passphrase)
            if not key.has_private():
                raise ValueError("The key is not a private key")
            return cls(None, key=key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Either Key format is invalid "
                "or passphrase is missing or incorrect.") from e
Exemplo n.º 32
0
def pycryptodome_ecdsa(count,loop):
    ecc_key = ECC.generate(curve='P-256')
    message = b'I give my permission to order #4355'
    h = SHA256.new(message)

    signer = DSS.new(ecc_key, 'fips-186-3')
    time_list_sign = []
    for l in range(loop):
        start = time.time()
        for c in range (count):
            signature = signer.sign(h)
        end = time.time() - start
        # print("["+str(l)+"th pycryptodomex_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature")
        time_list_sign.append(end)
    ave_sign = numpy.mean(numpy.array(time_list_sign))

    verifier = DSS.new(ecc_key, 'fips-186-3')
    time_list_vrfy = []
    for l in range(loop):
        start = time.time()
        for c in range (count):
            try:
                verifier.verify(h, signature)
            except ValueError:
                print ("The message is not authentiend")
        end = time.time() - start
        # print("["+str(l)+"th pycryptodomex_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature")
        time_list_vrfy.append(end)
    ave_vrfy = numpy.mean(numpy.array(time_list_vrfy))

    print("pycryptodomex_ecdsa:sign average second is "+ str(ave_sign) + "/"+str(count)+" signature")
    print("pycryptodomex_ecdsa:vrfy average second is "+ str(ave_vrfy) + "/"+str(count)+" signature")
    return time_list_sign, time_list_vrfy
Exemplo n.º 33
0
def generate_signature():
    """
    Genera una clave ECDSA.

    :return: Una clave ECDSA.
    """
    return ECC.generate(curve=CURVE)
Exemplo n.º 34
0
    def add_tests(self, filename):
        comps = "Cryptodome.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)
Exemplo n.º 35
0
    def test_export_public_der_compressed(self):
        key_file = load_file("ecc_p256_public.der")
        pub_key = ECC.import_key(key_file)
        key_file_compressed = pub_key.export_key(format="DER", compress=True)

        key_file_compressed_ref = load_file("ecc_p256_public_compressed.der")
        self.assertEqual(key_file_compressed, key_file_compressed_ref)
Exemplo n.º 36
0
    def test_unsupported_curve(self):

        # openssl ecparam -name secp224r1 -genkey -noout -out strange-curve.pem -conv_form uncompressed
        curve = """-----BEGIN EC PRIVATE KEY-----
MGgCAQEEHEi7xTHW+5oT8wgpjoEKV7uwMuY8rt2YUZe4j1SgBwYFK4EEACGhPAM6
AATJgfOG+Bnki8robpNM8MtArji43GU9up4B0x9sVhqB+fZP+hXgV9ITN7YX4E/k
gVnJp9EBND/tHQ==
-----END EC PRIVATE KEY-----"""

        from Cryptodome.PublicKey.ECC import UnsupportedEccFeature
        try:
            ECC.import_key(curve)
        except UnsupportedEccFeature as uef:
            assert("1.3.132.0.33" in str(uef))
        else:
            assert(False)
Exemplo n.º 37
0
    def test_export_public_der_compressed(self):
        key_file = load_file("ecc_p256_public.der")
        pub_key = ECC.import_key(key_file)
        key_file_compressed = pub_key.export_key(format="DER", compress=True)

        key_file_compressed_ref = load_file("ecc_p256_public_compressed.der")
        self.assertEqual(key_file_compressed, key_file_compressed_ref)
Exemplo n.º 38
0
    def test_mix(self):

        p1 = ECC.generate(curve='P-256').pointQ
        p2 = ECC.generate(curve='P-384').pointQ

        try:
            p1 + p2
            assert (False)
        except ValueError as e:
            assert "not on the same curve" in str(e)

        try:
            p1 += p2
            assert (False)
        except ValueError as e:
            assert "not on the same curve" in str(e)
Exemplo n.º 39
0
async def verify_known_ecdsa_signature(name: FormalName,
                                       sig: SignaturePtrs) -> bool:
    global client_self_signed

    sig_info = sig.signature_info
    covered_part = sig.signature_covered_part
    sig_value = sig.signature_value_buf
    if not sig_info or sig_info.signature_type != SignatureType.SHA256_WITH_ECDSA:
        return False
    if not covered_part or not sig_value:
        return False
    try:
        key_bits = bytes(client_self_signed.content)
    except (KeyError, AttributeError):
        logging.debug('Cannot load pub key from received certificate')
        return False
    pk = ECC.import_key(key_bits)
    verifier = DSS.new(pk, 'fips-186-3', 'der')
    sha256_hash = SHA256.new()
    for blk in covered_part:
        sha256_hash.update(blk)
    try:
        verifier.verify(sha256_hash, bytes(sig_value))
    except ValueError:
        return False
    return True
Exemplo n.º 40
0
def get_prv_key_from_safe_bag(id_name):
    """
    Export the safebag with password 1234 using ndnsec-export command line tool.
    The function then parse the exported safe bag and return the private key bytes.

    :param id_name: the NDN identity name
    """
    p = subprocess.run(['ndnsec-export', id_name, '-P', '1234'],
                       stdout=subprocess.PIPE)
    wire = base64.b64decode(p.stdout)
    logging.debug('result from ndnsec-export')
    logging.debug(wire)
    wire = parse_and_check_tl(wire, SecurityV2TypeNumber.SAFE_BAG)
    bag = SafeBag.parse(wire)
    # Don't use unwrap because the key returned is still in DER format
    #key = unwrap(bytes(bag.encrypted_key_bag), '1234')[1]
    privateKey = serialization.load_der_private_key(bytes(
        bag.encrypted_key_bag),
                                                    password=b'1234',
                                                    backend=default_backend())
    ecc_key = ECC.import_key(
        privateKey.private_bytes(Encoding.DER, PrivateFormat.PKCS8,
                                 NoEncryption()))
    logging.debug("pub key: ")
    logging.debug(ecc_key.pointQ.xy)
    logging.debug("prv key: ")
    logging.debug(ecc_key.d)
    cert_prv_key = ecc_key.d.to_bytes()
    logging.info("Private KEY: ")
    logging.info(cert_prv_key)
    return cert_prv_key
Exemplo n.º 41
0
    def add_tests(self, filename):
        comps = "Cryptodome.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 test_export_private_pkcs8_encrypted(self):
        encoded = ref_private._export_pkcs8(passphrase="secret",
                                            protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC._import_pkcs8, encoded, None)

        decoded = ECC._import_pkcs8(encoded, "secret")
        self.assertEqual(ref_private, decoded)

        # ---

        encoded = ref_private.export_key(format="DER",
                                         passphrase="secret",
                                         protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)
Exemplo n.º 43
0
    def test_export_public_pem_compressed(self):
        key_file = load_file("ecc_p256_public.pem", "rt").strip()
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="PEM", compress=True)
        key_file_compressed_ref = load_file("ecc_p256_public_compressed.pem", "rt").strip()

        self.assertEqual(key_file_compressed, key_file_compressed_ref)
Exemplo n.º 44
0
    def test_equality(self):

        private_key = ECC.construct(d=3, curve="P-256")
        private_key2 = ECC.construct(d=3, curve="P-256")
        private_key3 = ECC.construct(d=4, curve="P-256")

        public_key = private_key.public_key()
        public_key2 = private_key2.public_key()
        public_key3 = private_key3.public_key()

        self.assertEqual(private_key, private_key2)
        self.assertNotEqual(private_key, private_key3)

        self.assertEqual(public_key, public_key2)
        self.assertNotEqual(public_key, public_key3)

        self.assertNotEqual(public_key, private_key)
    def test_export_private_pem_encrypted(self):
        encoded = ref_private._export_private_pem(passphrase=b("secret"))

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "EC PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)

        # ---

        encoded = ref_private.export_key(format="PEM",
                                         passphrase="secret",
                                         use_pkcs8=False)
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)
    def test_export_private_pkcs8_and_pem_2(self):
        # PKCS8 inside PEM with PKCS8 encryption
        encoded = ref_private._export_private_encrypted_pkcs8_in_clear_pem("secret",
                              protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "ENCRYPTED PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)

        # ---

        encoded = ref_private.export_key(format="PEM",
                                         passphrase="secret",
                                         protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)
Exemplo n.º 47
0
    def test_compressed_curve(self):

        # Compressed P-256 curve (Y-point is even)
        pem1 = """-----BEGIN EC PRIVATE KEY-----
        MFcCAQEEIHTuc09jC51xXomV6MVCDN+DpAAvSmaJWZPTEHM6D5H1oAoGCCqGSM49
        AwEHoSQDIgACWFuGbHe8yJ43rir7PMTE9w8vHz0BSpXHq90Xi7/s+a0=
        -----END EC PRIVATE KEY-----"""

        # Compressed P-256 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
        MFcCAQEEIFggiPN9SQP+FAPTCPp08fRUz7rHp2qNBRcBJ1DXhb3ZoAoGCCqGSM49
        AwEHoSQDIgADLpph1trTIlVfa8NJvlMUPyWvL+wP+pW3BJITUL/wj9A=
        -----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0xA6FC)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0x6E57)
Exemplo n.º 48
0
    def test_construct(self):

        key = ECC.construct(curve="P-256", d=1)
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        key = ECC.construct(curve="P-256", point_x=_curve.Gx, point_y=_curve.Gy)
        self.failIf(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        # Other names
        ECC.construct(curve="secp256r1", d=1)
        ECC.construct(curve="prime256v1", d=1)
    def test_import_private_pkcs8_in_pem_clear(self):
        key_file = load_file("ecc_p256_private_p8_clear.pem")

        key = ECC.import_key(key_file)
        self.assertEqual(ref_private, key)
Exemplo n.º 50
0
                                 {'result': lambda x: x,
                                  'qx': lambda x: int(x, 16),
                                  'qy': lambda x: int(x, 16),
                                  })

for idx, tv in enumerate(test_vectors_verify):

    if isinstance(tv, basestring):
        res = re.match("\[P-256,(SHA-[0-9]+)\]", tv)
        assert res
        hash_name = res.group(1).replace("-", "")
        hash_module = load_hash_by_name(hash_name)
        continue

    hash_obj = hash_module.new(tv.msg)
    key = ECC.construct(curve="P-256", point_x=tv.qx, point_y=tv.qy)
    verifier = DSS.new(key, 'fips-186-3')

    def positive_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        verifier.verify(hash_obj, signature)

    def negative_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        self.assertRaises(ValueError, verifier.verify, hash_obj, signature)

    if tv.result.startswith('p'):
        setattr(FIPS_ECDSA_Tests, "test_verify_positive_%d" % idx, positive_test)
    else:
        setattr(FIPS_ECDSA_Tests, "test_verify_negative_%d" % idx, negative_test)


test_vectors_sign = load_tests(("Cryptodome", "SelfTest", "Signature", "test_vectors", "ECDSA"),
    def test_import_x509_pem(self):
        key_file = load_file("ecc_p256_x509.pem")

        key = ECC.import_key(key_file)
        self.assertEqual(ref_public, key)
    def test_import_private_pem(self):
        key_file = load_file("ecc_p256_private.pem")

        key = ECC.import_key(key_file)
        self.assertEqual(ref_private, key)
Exemplo n.º 53
0
from jwkest.jwk import ECKey
from Cryptodome.PublicKey import ECC

ecc_key = ECC.generate(curve='P-256')
jwk = ECKey(key=ecc_key)
jwk.serialize(private=True)