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")
Exemple #2
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")
Exemple #3
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")
Exemple #4
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")
Exemple #5
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")
Exemple #6
0
def generate_keys(key_type, key_scope, key_format='der'):
    """ generates private and public keys:
        - key_type designates the type of the key: 'rsa', 'dsa', 'ecc'
        - key_format designates the key representation 'der' or 'pem'
        - key_scope designates the scope of the key: 'sig', 'enc' -- this is
          mostly for naming convention
        output files are:
            key-<key_type>-<key_scope>-{pkcs8,asn1}.<key_format>
    """
    pbl, prv = get_key_files(key_type, key_scope, key_format=key_format)

    if key_format == 'der':
        key_format = 'DER'
    if key_format == 'pem':
        key_format = 'PEM'

    if key_type == 'rsa':
        key = RSA.generate(2048)
        bytes_prv = key.exportKey(key_format, pkcs=8)
        bytes_pbl = key.publickey().exportKey(key_format)
    elif key_type == 'dsa':
        key = DSA.generate(2048)
        bytes_prv = key.exportKey(key_format, pkcs8=True)
        bytes_pbl = key.publickey().exportKey(key_format)
    elif key_type == 'ecc':
        key = ECC.generate(curve='P-256')
        bytes_prv = key.export_key(format=key_format, use_pkcs8=True)
        bytes_pbl = key.public_key().export_key(format=key_format)
    else:
        raise ImplementationError(key_type, "Unknown key type")

    with open(prv, 'wb') as f:
        f.write(bytes_prv)
    with open(pbl, 'wb') as f:
        f.write(bytes_pbl)
Exemple #7
0
def generate_signature():
    """
    Genera una clave ECDSA.

    :return: Una clave ECDSA.
    """
    return ECC.generate(curve=CURVE)
Exemple #8
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)
Exemple #9
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
Exemple #10
0
 def __init__(self, curve: str, **kwargs):
     if kwargs:
         self._key = kwargs.pop("key")
         return
     try:
         self._key = ECC.generate(curve=CURVES[curve])
     except KeyError as e:
         raise ValueError(f"Invalid curve: {curve}") from e
Exemple #11
0
 def generate_RG_with_input_key(self, n, pk, sk):
     self.__pkeys = []
     for i in range(0, n - 1):
         self.__key = ECC.generate(curve='secp256r1')
         self.__pkeys.append(
             (self.__key.pointQ.x.__int__(), self.__key.pointQ.y.__int__()))
     self.__pkeys.append(pk)
     random.shuffle(self.__pkeys)
     return self.__pkeys, (pk, sk)
def generateKeypair(keyname):
    try:
        fname = keyname.translate(string.maketrans('', ''), '<>:"/\\|?*')
        key = ECC.generate(curve='P-256')
        with open(config.KEY_PATH + os.sep + fname + '.pem', 'w') as f:
            f.write(key.export_key(format='PEM'))
            print 'Private key generated: ' + fname
        return key
    except:
        raise Exception('Error trying to generate key with given identifier.')
Exemple #13
0
    def _handle_msg1_msg2(self):
        # Generate local key pair
        self.Gb = ECC.generate(curve=self.CURVE_NAME)

        # derive_shared_key
        shared_point = self.Ga.pointQ * self.Gb.d
        shared_secret = _dump_int(shared_point.x, 32)

        cmac_key = b'\x00' * 16
        self.kdk = _aes_cmac(key=cmac_key, msg=shared_secret)
        self.smk = _aes_cmac(key=self.kdk, msg=self.SEED_SMK)
Exemple #14
0
def new_wallet():
    random_gen = Cryptodome.Random.new().read
    private_key = ECC.generate(curve='P-256')
    public_key = private_key.public_key()
    response = {
        'private_key':
        binascii.hexlify(private_key.export_key(format='DER')).decode('ascii'),
        'public_key':
        binascii.hexlify(public_key.export_key(format='DER')).decode('ascii')
    }

    return jsonify(response), 200
Exemple #15
0
 def test_verify(self):
     # Ecdsa signature is not unique, so we only test if we can verify it
     pri_key = ECC.generate(curve="P-256")
     key = pri_key.export_key(format="DER")
     pub_key = pri_key.public_key()
     signer = Sha256WithEcdsaSigner("/K/KEY/x", key)
     pkt = make_data("/test", MetaInfo(), b"test content", signer=signer)
     _, _, _, sig_ptrs = parse_data(pkt)
     # Test its format is ASN.1 der format
     DerSequence().decode(bytes(sig_ptrs.signature_value_buf))
     validator = EccChecker.from_key(
         "/K/KEY/x", bytes(pub_key.export_key(format='DER')))
     assert aio.run(validator(Name.from_str("/test"), sig_ptrs))
Exemple #16
0
 def generate_key(self, id_name: FormalName, key_type: str = 'rsa', **kwargs) -> Tuple[FormalName, BinaryStr]:
     if key_type == 'rsa':
         siz = kwargs.pop('key_size', 2048)
         pri_key = RSA.generate(siz)
         pub_key = pri_key.publickey().export_key(format='DER')
         key_der = pri_key.export_key(format='DER', pkcs=1)
     elif key_type == 'ec':
         siz = kwargs.pop('key_size', 256)
         pri_key = ECC.generate(curve=f'P-{siz}')
         pub_key = bytes(pri_key.public_key().export_key(format='DER'))
         key_der = pri_key.export_key(format='DER', use_pkcs8=False)
     else:
         raise ValueError(f'Unsupported key type {key_type}')
     key_name = self.construct_key_name(id_name, pub_key, **kwargs)
     self.save_key(key_name, key_der)
     return key_name, pub_key
Exemple #17
0
 def test_verify(self):
     # Ecdsa signature is not unique, so we only test if we can verify it
     pri_key = ECC.generate(curve="P-256")
     key = pri_key.export_key(format="DER")
     pub_key = pri_key.public_key()
     signer = Sha256WithEcdsaSigner("/K/KEY/x", key)
     pkt = make_data("/test", MetaInfo(), b"test content", signer=signer)
     _, _, _, sig_ptrs = parse_data(pkt)
     # Test its format is ASN.1 der format
     DerSequence().decode(bytes(sig_ptrs.signature_value_buf))
     verifier = DSS.new(pub_key, 'fips-186-3', 'der')
     h = SHA256.new()
     for content in sig_ptrs.signature_covered_part:
         h.update(content)
     # verify() throws ValueError if it fails, the return value is undefined
     # So do not assert its value
     verifier.verify(h, bytes(sig_ptrs.signature_value_buf))
 def __init__(self):
     super().__init__()
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.currentBalance = 10
     self.simulatorBalance = 100
     if not os.path.exists('simulatorpublickey.pem'):
         self.key = ECC.generate(curve='P-256')
         f = open('simulatorpublickey.pem', 'wt')
         f.write(key.public_key().export_key(format='PEM'))
         f.close()
         f = open('simulatorprivatekey.pem', 'wt')
         f.write(key.export_key(format='PEM'))
         f.close()
         return
     else:
         f = open('simulatorprivatekey.pem', 'rt')
         self.key = ECC.import_key(f.read())
         f.close()
     return
Exemple #19
0
    def __init__(self):
        # contains active jobs
        self.pool_jobs = []
        # contains jobs done
        self.jobs_done = []
        # job_id => job
        self.jobs = {}
        # user_id => credit
        self.user_credits = {}
        # results to be verified
        self.to_check = []
        # job_id => JOB_DONE
        self.results = {}

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('', 5599))
        sock.listen(50)
        self.sock = sock
        self.inputs = [sock]
        self.outputs = []
        self.message_queues = {}

        self.key = None
        self.public_key = None

        if not os.path.exists('myprivatekey.pem'):
            print("creating new ECC private key")
            self.key = ECC.generate(curve='P-256')
            f = open('mypublickey.pem', 'wt')
            f.write(self.key.public_key().export_key(format='PEM'))
            f = open('myprivatekey.pem', 'wt')
            f.write(self.key.export_key(format='PEM'))
            f.close()
        else:
            print("reading existing key")
            f = open('myprivatekey.pem', 'rt')
            self.key = ECC.import_key(f.read())
            f.close()
        self.public_key = self.key.public_key().export_key(format='PEM')
        self.user_credits[self.public_key] = 100
        print("BlockchainController init end")
Exemple #20
0
def DummyClient():
    """Starts a TCP client
    Connects to server
    Pings some data off of the server
    """
    host = "127.0.0.1"  #loopback adress
    port = 5555

    socket1 = socket.socket()
    socket1.settimeout(1)
    socket1.connect((host, port))

    key = ECC.generate(curve='P-256')
    publicKey = key.public_key().export_key(format='DER', compress=True).hex()
    print("publicKey :" +
          str(key.public_key().export_key(format='DER', compress=True)))
    protocallVersion = "0000"

    version = 'v0.0'
    clientName = "DummyClient"
    message = publicKey + ":" + protocallVersion + ":" + "bisclient" + ":" + clientName + ":" + version + ":"
    message = message.ljust(192, ' ')

    h1 = SHA256.new(message.ljust(256, " ").encode('utf-8'))
    signer = DSS.new(key, 'fips-186-3')
    signature = signer.sign(h1)
    handshake = message.encode('utf-8') + signature

    print("Sending data: " + str(handshake.hex()))
    socket1.send(handshake)

    data = socket1.recv(256)
    print("\tRecived data: " + str(data.hex()))

    #all communication should be encrypted beyond this point

    data = socket1.recv(4096).decode('utf-8')
    print("\tRecived data: " + str(data))

    socket1.close()
    def __init__(self):
        self.chain = []
        self.nodes = set()
        # Create a unique global address
        private_key = ECC.generate(curve='P-256')
        public_key = private_key.public_key()
        file_out = open("private.txt", "w")
        file_out.write(
            binascii.hexlify(
                private_key.export_key(format='DER')).decode('ascii'))

        file_out = open("receiver.txt", "w")
        file_out.write(
            binascii.hexlify(
                public_key.export_key(format='DER')).decode('ascii'))

        self.node_id = binascii.hexlify(
            public_key.export_key(format='DER')).decode('ascii')

        self.transactions = []

        # I haven't settled on a proof yet, looking into proof of stake
        self.new_block(previous_hash=1, proof=100)
Exemple #22
0
class FIPS_ECDSA_Tests(unittest.TestCase):

    key_priv = ECC.generate(curve="P-256")
    key_pub = key_priv.public_key()

    def shortDescription(self):
        return "FIPS ECDSA Tests"

    def test_loopback(self):
        hashed_msg = SHA512.new(b("test"))
        signer = DSS.new(self.key_priv, 'fips-186-3')
        signature = signer.sign(hashed_msg)

        verifier = DSS.new(self.key_pub, 'fips-186-3')
        verifier.verify(hashed_msg, signature)

    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Cryptodome.Hash import SHA1

        self.description = "Unapproved hash (SHA-1) test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)

    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())
Exemple #23
0
 def generate_ecdsa_key():
     return ECC.generate(curve='prime256v1')
Exemple #24
0
class FIPS_ECDSA_Tests(unittest.TestCase):

    key_priv = ECC.generate(curve="P-256")
    key_pub = key_priv.public_key()

    def shortDescription(self):
        return "FIPS ECDSA Tests"

    def test_loopback(self):
        hashed_msg = SHA512.new(b("test"))
        signer = DSS.new(self.key_priv, 'fips-186-3')
        signature = signer.sign(hashed_msg)

        verifier = DSS.new(self.key_pub, 'fips-186-3')
        verifier.verify(hashed_msg, signature)

    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Cryptodome.Hash import SHA1

        self.description = "Unapproved hash (SHA-1) test"
        hash_obj = SHA1.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)

    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())

    def test_negative_unknown_modes_encodings(self):
        """Verify that unknown modes/encodings are rejected"""

        self.description = "Unknown mode test"
        self.assertRaises(ValueError, DSS.new, self.key_priv, 'fips-186-0')

        self.description = "Unknown encoding test"
        self.assertRaises(ValueError, DSS.new, self.key_priv, 'fips-186-3',
                          'xml')

    def test_asn1_encoding(self):
        """Verify ASN.1 encoding"""

        self.description = "ASN.1 encoding test"
        hash_obj = SHA256.new()
        signer = DSS.new(self.key_priv, 'fips-186-3', 'der')
        signature = signer.sign(hash_obj)

        # Verify that output looks like a DER SEQUENCE
        self.assertEqual(bord(signature[0]), 48)
        signer.verify(hash_obj, signature)

        # Verify that ASN.1 parsing fails as expected
        signature = bchr(7) + signature[1:]
        self.assertRaises(ValueError, signer.verify, hash_obj, signature)
Exemple #25
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Cryptodome.PublicKey import ECC
import time
"""
该部分用于系统初始化,产生UE,Operator,A3VI的公私钥对,并形成证书存储。
"""
print("---------------开始生成公私钥文件-------------------")
t1 = time.clock()
key_UE = ECC.generate(curve='secp256r1')
f = open(r'D:\PythonProject\FUIH\ECC_file_keys\UE_privatekey.pem', 'wt')
f.write(key_UE.export_key(format='PEM'))
f.close()

t = open(r'D:\PythonProject\FUIH\ECC_file_keys\UE_publickey.pem', 'wt')
publickey = key_UE.public_key()
t.write(publickey.export_key(format='PEM'))
t.close()
print("UE CPU执行时间:", (time.clock() - t1) * 1000, 'ms')

t2 = time.clock()
key_Ope = ECC.generate(curve='secp256r1')
f = open(r'D:\PythonProject\FUIH\ECC_file_keys\Ope_privatekey.pem', 'wt')
f.write(key_Ope.export_key(format='PEM'))
f.close()

t = open(r'D:\PythonProject\FUIH\ECC_file_keys\Ope_publickey.pem', 'wt')
publickey = key_Ope.public_key()
t.write(publickey.export_key(format='PEM'))
t.close()
print("Ope CPU执行时间:", (time.clock() - t2) * 1000, 'ms')
Exemple #26
0
import time
import traceback
import json
import paho.mqtt.client as mqtt

from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import ECC
from Cryptodome.Signature import DSS

try:
    print('Loading keys...')
    priv_key = ECC.import_key(open('privkey.pem').read())
    pub_key_str = open('pubkey.pem').read()
except FileNotFoundError:
    print('Keys not found, generating...')
    key = ECC.generate(curve='p521')
    print('Generation complete.')
    priv_key = key.export_key(format='PEM')
    file_out = open("privkey.pem", "w")
    file_out.write(priv_key)
    file_out.close()
    priv_key = ECC.import_key(priv_key)

    pub_key_str = key.public_key().export_key(format='PEM')
    file_out = open("pubkey.pem", "w")
    file_out.write(pub_key_str)
    file_out.close()

threshold = int('f' * 64, 16) // 300000
block = {
    "id": 0,
Exemple #27
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)
Exemple #28
0
from Cryptodome.PublicKey import ECC
from Cryptodome.Signature import DSS
from Cryptodome.Hash import SHA256


private_key = ECC.generate(curve="P-256") # $ PublicKeyGeneration keySize=256
public_key = private_key.public_key()

# ------------------------------------------------------------------------------
# sign/verify
# ------------------------------------------------------------------------------

print("sign/verify")


message = b"message"

signer = DSS.new(private_key, mode='fips-186-3')

hasher = SHA256.new(message) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message
signature = signer.sign(hasher) # $ CryptographicOperation CryptographicOperationInput=hasher # MISSING: CryptographicOperationAlgorithm=ECDSA

print("signature={}".format(signature))

print()

verifier = DSS.new(public_key, mode='fips-186-3')

hasher = SHA256.new(message) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message
verifier.verify(hasher, signature) # $ CryptographicOperation CryptographicOperationInput=hasher CryptographicOperationInput=signature
print("Signature verified (as expected)")
Exemple #29
0
 def _generateKeypair(size):
     key = ECC.generate(curve=curve)
     privKey = key.export_key(format='PEM')
     pubKey = key.public_key().export_key(format='PEM')
     return privKey, pubKey
Exemple #30
0
 def __init__(self):
     self.__P = ECC._curves['P-256'].G  # 这个是base point
     # self.__P = P  # 这个是base point
     self.__order = ECC._curves['P-256'].order.__int__()  # P点的阶数 注意是int类型的
     # self.__order = order  # P点的阶数 注意是int类型的
     self.__curve = ECC.generate(curve='P-256')  # 指定并生成椭圆曲线 P-256 = secp256r1