コード例 #1
0
def test_merkle_tree():
    sender_key = ECC.generate(curve='P-256')
    sender_address = Address(bytes(sender_key.public_key().export_key(format='DER')))
    receiver_key = ECC.generate(curve='P-256')
    receiver_address = Address(bytes(receiver_key.public_key().export_key(format='DER')))

    transaction1 = Transaction(sender_address, receiver_address, 100, b'random', None)
    transaction1.sign(sender_key)
    transaction2 = Transaction(sender_address, receiver_address, 50, b'random', None)
    transaction2.sign(sender_key)
    transaction3 = Transaction(receiver_address, sender_address, 10, b'random', None)
    transaction3.sign(receiver_key)
    transaction4 = Transaction(sender_address, receiver_address, 60, b'random', None)
    transaction4.sign(sender_key)
    transaction5 = Transaction(receiver_address, sender_address, 80, b'random', None)
    transaction5.sign(receiver_key)

    tree = MerkleTree([transaction1, transaction2, transaction3, transaction4, transaction5])

    assert tree.root.left is not None
    assert tree.root.left.left.left.hash == bytes(transaction1.hash().digest())
    assert tree.root.left.left.right.hash == bytes(transaction2.hash().digest())
    assert tree.root.left.right.left.hash == bytes(transaction3.hash().digest())
    assert tree.root.left.right.right.hash == bytes(transaction4.hash().digest())
    assert tree.root.right.hash == bytes(transaction5.hash().digest())
コード例 #2
0
def test_deep_pki():
    root_key = ECC.generate(curve='P-256')
    root = Issuer(bytes(root_key.export_key(format='DER')))

    issuer2_key = ECC.generate(curve='P-256')
    issuer2_key_bytes = bytes(issuer2_key.export_key(format='DER'))
    issuer2_public_key_bytes = bytes(
        issuer2_key.public_key().export_key(format='DER'))
    issuer2 = Issuer(issuer2_key_bytes, root.issue(issuer2_public_key_bytes))

    issuer3_key = ECC.generate(curve='P-256')
    issuer3_key_bytes = bytes(issuer3_key.export_key(format='DER'))
    issuer3_public_key_bytes = bytes(
        issuer3_key.public_key().export_key(format='DER'))
    issuer3 = Issuer(issuer3_key_bytes,
                     issuer2.issue(issuer3_public_key_bytes))

    holder_key = ECC.generate(curve='P-256')
    holder = Holder(bytes(holder_key.export_key(format='DER')))
    certs = issuer3.issue(holder.public_key())
    holder.set_cert(certs)

    verifier = Verifier(root.public_key())
    nonce = b'20201111'
    certs, sign = holder.present(nonce)

    assert len(root.cert_chain) == 0
    assert len(issuer2.cert_chain) == 1
    assert len(issuer3.cert_chain) == 2
    assert len(holder.cert) == 3

    assert verifier.verify(certs, holder.public_key(), nonce, sign)
コード例 #3
0
def test_merkle_root():
    sender_key = ECC.generate(curve='P-256')
    sender_address = Address(bytes(sender_key.public_key().export_key(format='DER')))
    receiver_key = ECC.generate(curve='P-256')
    receiver_address = Address(bytes(receiver_key.public_key().export_key(format='DER')))

    transaction1 = Transaction(sender_address, receiver_address, 100, b'random', None)
    transaction1.sign(sender_key)
    transaction2 = Transaction(sender_address, receiver_address, 50, b'random', None)
    transaction2.sign(sender_key)
    transaction3 = Transaction(receiver_address, sender_address, 10, b'random', None)
    transaction3.sign(receiver_key)
    transaction4 = Transaction(sender_address, receiver_address, 60, b'random', None)
    transaction4.sign(sender_key)

    tree = MerkleTree([transaction1, transaction2, transaction3, transaction4])
    h1 = SHA256.new()
    h1.update(transaction1.hash().digest())
    h1.update(transaction2.hash().digest())
    h2 = SHA256.new()
    h2.update(transaction3.hash().digest())
    h2.update(transaction4.hash().digest())
    h3 = SHA256.new()
    h3.update(h1.digest())
    h3.update(h2.digest())
    root = h3.digest()

    assert tree.merkle_root() == root
コード例 #4
0
ファイル: pw_pkcrypto.py プロジェクト: rchatterjee/pam-typopw
def _derive_key(pw, sa, for_):
    """derives the ECC public key from the password using the salt.
    @pw (byte string): password
    @sa (byte string): salt (must be >= 16 bytes long)
    @for_ (string): allowed values, ('encryption', 'decryption',
                                     'verify', 'sign', 'both)
    @Returns: the pwhash and one or two ECC element (depending on the for_)
    """
    curve = 'secp256r1'  #
    intermediate_hash = PBKDF2(pw, sa, dkLen=16, count=HASH_CNT)  # SLOW
    pwhash = hash256(
        intermediate_hash)  # The last hash to be stored in the cache
    seed_enc = hash256(intermediate_hash, b'encryption|decryption')
    seed_sgn = hash256(intermediate_hash, b'sign|verify')
    prg_enc = RandomWSeed(seed_enc, 1024)
    prg_sgn = RandomWSeed(seed_sgn, 1024)
    if for_ == 'both':
        return (pwhash, (ECC.generate(curve=curve,
                                      randfunc=prg_enc.get_random_bytes),
                         ECC.generate(curve=curve,
                                      randfunc=prg_sgn.get_random_bytes)))
    elif for_ in ('encryption', 'decryption'):
        return pwhash, ECC.generate(curve=curve,
                                    randfunc=prg_enc.get_random_bytes)
    elif for_ in ('sign', 'verify'):
        return pwhash, ECC.generate(curve=curve,
                                    randfunc=prg_sgn.get_random_bytes)
コード例 #5
0
ファイル: test_ECC.py プロジェクト: 1dividedby0/ThermaApp
    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")
コード例 #6
0
ファイル: test_ECC.py プロジェクト: shubhanus/taiga
    def test_generate(self):

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

        # Other names
        ECC.generate(curve="secp256r1")
        ECC.generate(curve="prime256v1")
コード例 #7
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")
コード例 #8
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    def test_generate(self):

        curve = _curves['p521']
        key = ECC.generate(curve="P-521")
        self.failUnless(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")
コード例 #9
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")
コード例 #10
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")
コード例 #11
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    def test_generate(self):

        key = ECC.generate(curve="P-256")
        self.failUnless(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")
コード例 #12
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")
コード例 #13
0
def test_pki():
    root_key = ECC.generate(curve='P-256')
    root = Issuer(bytes(root_key.export_key(format='DER')))

    holder_key = ECC.generate(curve='P-256')
    holder = Holder(bytes(holder_key.export_key(format='DER')))
    certs = root.issue(holder.public_key())
    holder.set_cert(certs)

    verifier = Verifier(root.public_key())
    nonce = b'123'
    certs, sign = holder.present(nonce)
    assert verifier.verify(certs, holder.public_key(), nonce, sign)
コード例 #14
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    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)
コード例 #15
0
def generate_keys():

    key = ECC.generate(curve='P-256')
    private_key = key.export_key(format='PEM')
    public_key = key.public_key().export_key(format='PEM')

    return private_key, public_key
コード例 #16
0
def test_no_ca():
    holder_key = ECC.generate(curve='P-256')
    holder = Holder(bytes(holder_key.export_key(format='DER')))
    verifier = Verifier(b'')
    nonce = b'20201111'
    certs, sign = holder.present(nonce)
    assert not verifier.verify(certs, holder.public_key(), nonce, sign)
コード例 #17
0
 def verify(self, message):
     key = ECC.generate(
         curve='P-521'
     )  #Genera una nueva llave privada usando la curva definida por P-521
     h = SHA512.new(message)  #Genera la función Hash del mensaje.
     signer = DSS.new(
         key, 'fips-186-3')  #Crea un objeto signature para hacer la firma.
     signature = signer.sign(h)  #Genera la firma del mensaje.
     pubKey = key.public_key(
     )  #Obtiene la llave pública del par generado almacenado en "key".
     start_time = timer()  #Función que permite iniciar una toma de tiempo.
     verifier = DSS.new(
         pubKey, 'fips-186-3'
     )  #Crea un objeto signature para hacer la validación de la firma.
     try:
         verifier.verify(
             h, signature
         )  #Hace la comparación entre el hash del mensaje y la firma.
         print("La firma se pudo validar, es correcta.")
         self.executionTime = timer(
         ) - start_time  #Fin de la toma de tiempo.
         return 1
     except (
             ValueError
     ):  #Accede en caso de que los valores no sean correctos, es decir, la firma no es válida.
         print("La firma no se pudo validar, no es correcta")
         self.executionTime = timer(
         ) - start_time  #Fin de la toma de tiempo.
         return 0
コード例 #18
0
	def test():
		key = ECC.generate(curve='secp256r1')
		print key.public_key()
		x = key.public_key().pointQ.x
		y = key.public_key().pointQ.y

		hx=hex(int(str(x)))
		bytearray.fromhex(hx[2:64])[::-1]
		reversed_arr=result[::-1]

		x=key.public_key().pointQ.x
		hx=hex(int(str(x)))
		rx = bytearray.fromhex(hx[2:66])[::-1]


		y=key.public_key().pointQ.y
		hy=hex(int(str(y)))
		ry = bytearray.fromhex(hy[2:66])[::-1]	

		''.join('{:02x}'.format(x) for x in rx+ry)

		addr=SHA256.new(rx+ry).hexdigest()[:40]


		"".join("{:02x}".format(ord(c)) for c in pps)


		p = ECC.construct(curve='secp256r1',d=70054409939411066367955879351487264564474994114056648764946442729447023254584)
		signer = DSS.new(p, 'fips-186-3')
		pps=signer.sign(h)
コード例 #19
0
    def __gen_sym_key(device_public_key_string_xy):

        _ECC_CURVE = 'secp256r1'

        # Construct ECC point from device public key
        device_kpub_int_x = int.from_bytes(device_public_key_string_xy[:32], byteorder='big')
        device_kpub_int_y = int.from_bytes(device_public_key_string_xy[32:], byteorder='big')
        device_kpub_p = ECC.construct(curve=_ECC_CURVE, point_x=device_kpub_int_x, point_y=device_kpub_int_y)

        # Create user private / public key pair
        user_key_pair = ECC.generate(curve=_ECC_CURVE)

        # The shared secret is calculated using the device public point and the private key.
        # The secret is the x-coordinate of the resulting point
        shared_secret_int = (device_kpub_p.pointQ * user_key_pair.d).x

        # Calculate symmetric key from shared secret using hmac-sha256 and static data "config"
        shared_secret_string = int(shared_secret_int).to_bytes(32, byteorder='big')
        h = HMAC.new(shared_secret_string, msg=b'config', digestmod=SHA256)

        # Truncate to get shared private key (16 bytes)
        symmetric_key = h.digest()[0:16]

        # Create public key byte strings
        user_kpub_string_x = int(user_key_pair.pointQ.x).to_bytes(32, byteorder='big')
        user_kpub_string_y = int(user_key_pair.pointQ.y).to_bytes(32, byteorder='big')

        return symmetric_key, user_kpub_string_x + user_kpub_string_y
コード例 #20
0
 def generate_from_pw(pw, salt, curve='P-256'):
     """Generates a ECC key pair using the randomness derived from pw, salt. 
     """
     rand_seed = PBKDF2(pw, salt, dkLen=16, count=HASH_CNT)
     rand_num_generator = RandomWSeed(rand_seed, 1024)
     return ECC.generate(curve=curve,
                         randfunc=rand_num_generator.get_random_bytes)
コード例 #21
0
    def setUpFiles(cls):
        cls.test_file_dir = os.path.join(os.path.dirname(__file__), "..",
                                         "testfiles")
        cls.test_file_dir = os.path.realpath(cls.test_file_dir)
        if not os.path.exists(cls.test_file_dir):
            os.mkdir(cls.test_file_dir)

        cls.private_key_passphrase = 'test-passphrase'
        cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem')
        cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem')
        cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem')

        if not os.path.exists(cls.rsa_key_path):
            with open(cls.rsa_key_path, 'w') as f:
                f.write(RSA_TEST_PRIVATE_KEY)

        if not os.path.exists(cls.rsa4096_key_path):
            key = RSA.generate(4096)
            private_key = key.export_key(passphrase=cls.private_key_passphrase,
                                         protection='PEM')
            with open(cls.rsa4096_key_path, "wb") as f:
                f.write(private_key)

        if not os.path.exists(cls.ec_p521_key_path):
            key = ECC.generate(curve='P-521')
            private_key = key.export_key(
                format='PEM',
                passphrase=cls.private_key_passphrase,
                use_pkcs8=True,
                protection='PBKDF2WithHMAC-SHA1AndAES128-CBC')
            with open(cls.ec_p521_key_path, "wt") as f:
                f.write(private_key)
コード例 #22
0
def ecc_pem_generate(length: int) -> tuple:
    ecc = ECC.generate(curve=f"P-{length}")

    private_pem = ecc.export_key(format="PEM")
    public_pem = ecc.public_key().export_key(format="PEM")

    return public_pem, private_pem
コード例 #23
0
ファイル: Maker.py プロジェクト: adleonis/Mnet
def create_key(algo, algotype):
    #algo is type <str> can be "RSA" or "ECC"
    #algotype is type <str> could be "P-256" for ECC algo, or "2048" for RSA algo
    #returns 2 encodings of the same generated keys
    if algo == "RSA":
        key = RSA.generate(int(algotype))
        private_key_der = key.export_key(format='DER')
        private_key_pem = key.export_key(format='PEM')
        public_key_PEM = key.publickey().export_key(format='PEM')
        public_key_DER = key.publickey().export_key(format='DER')
    elif algo == "ECC":
        key = ECC.generate(curve=algotype)
        private_key_der = key.export_key(format='DER')
        private_key_pem = key.export_key(format='PEM')
        public_key = ECC.import_key(private_key_der).public_key()
        public_key_PEM = public_key.export_key(format='PEM')
        public_key_DER = public_key.export_key(format='DER')
    else:
        print("This crypto is not implemented, try 'RSA' or 'ECC' ")
        return False
    return {
        'pubkDER': public_key_DER,
        'pkeyDER': private_key_der,
        'pubkPEM': public_key_PEM,
        'pkeyPEM': private_key_pem,
        'algo': algo,
        'algotype': algotype
    }
コード例 #24
0
def create_ecc_pair(curve_type: str):
    while True:
        ecc_key_pair = ECC.generate(curve=curve_type)
        private_key = ecc_key_pair.d.to_bytes()
        if len(private_key) == 32:
            break
    return ecc_key_pair
コード例 #25
0
def sign_up(request):
    if request.method == "POST":
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        password = request.POST.get('password')
        user_obj = User.objects.create(first_name=first_name, last_name=last_name, username=email, email=email)
        user_obj.set_password(password)
        user_obj.save()

        user_details_obj = UserDetail.objects.create(user=user_obj)

        # Generate Private key
        name = "{}_{}".format(user_obj.first_name, user_obj.last_name)
        key = ECC.generate(curve='P-256')
        private_key = key.export_key(format='PEM')

        print('**********************')
        print(private_key)
        print('**********************')

        # Generate Public Key

        f = open('utils/public_' + name + '.pem', 'wt')
        f.write(key.public_key().export_key(format='PEM'))
        f.close()

        user_details_obj.public_key = key.public_key().export_key(format='PEM')
        user_details_obj.save()

        messages.success(request, 'User Sign Up success..!')
        return redirect('/')

    elif request.method == "GET":
        return render(request, 'welcome/sign_up.html')
コード例 #26
0
def process_request_alias(author: AccountId, message: str, server: Server, **kwargs):
    """Processes a request for an alias code."""
    account = assert_is_account(author, server)

    split_msg = message.split()
    if len(split_msg) != 2:
        raise CommandException('Incorrect formatting. Expected `request-alias ALIAS_ACCOUNT_NAME`.')

    _, alias_name = split_msg
    alias_id = parse_account_id(alias_name)
    if server.has_account(alias_id):
        raise CommandException(
            'An account has already been associated with %s, so it cannot be an alias for this account.' %
            alias_id.readable())

    # To generate an alias code, we generate an ECC public/private key pair, use the
    # private key to generate a signed version of the aliased account name and associate
    # the public key with the account.
    key = ECC.generate(curve='P-256')
    signature = sign_message(str(alias_id), key)
    server.add_public_key(account, key.public_key())

    # At this point we will allow the private key to be forgotten.

    # Compose a helpful message for as to how the bot can be contacted to link accounts.
    if isinstance(alias_id, RedditAccountId):
        contact_message = 'Send me that exact command as a Reddit Private Message (not a direct chat) from %s.' % alias_id.readable()
    elif isinstance(alias_id, DiscordAccountId):
        contact_message = 'Send me that exact command prefixed with a mention of my name via Discord from account %s.' % alias_id
    else:
        contact_message = ''

    return ('I created an alias request code for you. '
        'Make {0} an alias for this account ({2}) by sending me the following message from {3}.\n\n```\nadd-alias {4} {1}\n```\n\n{5}').format(
            str(alias_id), signature, author.readable(), alias_id.readable(), str(author), contact_message)
コード例 #27
0
 def fill_key_pool(self):
     num_needed = self.key_poll_len - len(self.key_pool)
     if num_needed > 0:
         self.logger.info("Filling session key pool, %d" % num_needed)
         for _ in range(num_needed):
             key = ECC.generate(curve='P-256')
             self.key_pool.append(key)
コード例 #28
0
ファイル: utils.py プロジェクト: maximx1/vote_block
def generate_key_pair(passphrase):
    key = ECC.generate(curve='P-256')
    private_key = key.export_key(passphrase=passphrase,
                                 format='PEM',
                                 protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
    public_key = key.public_key().export_key(format='OpenSSH')
    return (public_key, private_key)
コード例 #29
0
def ECDSA_521(data):
    times = []

    key = ECC.generate(curve='P-521')
    h = SHA512.new(data)

    controler = DSS.new(key, 'fips-186-3')

    start = time.clock()
    signature = controler.sign(h)
    end = time.clock()

    print(signature.hex())
    times.append(end - start)

    try:
        start = time.clock()
        controler.verify(h, signature)
        end = time.clock()
        print('The message is authentic')
    except ValueError:
        print('The message is not authentic')

    times.append(end - start)

    return times
コード例 #30
0
def make_address(prefix: 'string') -> 'string':
    """
    generates a Helium address from a ECC public key in PEM format. 
    prefix is a single numeric character which describes the type of
    the address. This prefix must be '1'
    """

    key = ECC.generate(curve='P-256')
    __private_key = key.export_key(format='PEM')
    public_key = key.public_key().export_key(format='PEM')

    val = make_SHA256_hash(public_key)
    val = make_RIPEMD160_hash(val)
    tmp = prefix + val

    # make a checksum
    checksum = make_SHA256_hash(tmp)
    checksum = checksum[len(checksum) - 4:]

    # add the checksum to the tmp result
    address = tmp + checksum

    # encode addr as a base58 sequence of bytes
    address = base58.b58encode(address.encode())

    # The decode function converts a byte sequence to a string
    address = address.decode("ascii")

    return address
コード例 #31
0
def make_p256_keys_pbkdf2_branched(password, salt, key_amount = 1, branches = [410]):
	'''
	Make P-256 multiple key pairs at once from any string
	Brances implements additional layer of security. Branch is better be an integer, but, for real, it may be any string	
	Returns a list
	'''
	# password = sha000(password, 50)
	# salt = SHA256.new(password.encode()).digest()
	#print('salt',benc.encode(salt))
	count = int(str(int(benc.encode(salt),16))[0:5])

	master_key = PBKDF2(password, salt = str(salt), count=count) 
	
	def my_rand(n):
		my_rand.counter += 1
		return PBKDF2(master_key, "my_rand:%d" % my_rand.counter, dkLen=n, count=1)
	my_rand.counter = 0
	
	keys = []
	with progressbar.ProgressBar(max_value=key_amount) as bar_small:
		for tymes in range(key_amount):
			bar_small.update(tymes)
			key = PBKDF2(password, salt = (str(salt) + str(branches[tymes%len(branches)])), count = count)
			keys.append(ECC.generate(curve = 'P-256', randfunc=my_rand))
			password = key
	return list(enumerate(keys, start=1))	
コード例 #32
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)
コード例 #33
0
ファイル: pw_pkcrypto.py プロジェクト: rchatterjee/pam-typopw
def encrypt(_pk_dict, msg):
    """
    @pk_dict (dict): is a dictionary of id->pk, which will be used to encrypt
                     a message. pk's in the dict can be EccKey or basestring
    @msg (byte string): a message to be encrypted
    """
    # make a semi-deep copy of the pks
    pk_dict = {k: v for k, v in _pk_dict.items()}

    # First AES-128 encrypt the message with a random key
    aes_k = os.urandom(32)  # 32 byte = 256 bit

    # IV is not required for EAX mode
    nonce = os.urandom(16)  # the key is generated random every time so, small
    # nonce is OK
    ctx, tag = AES.new(key=aes_k, mode=AES.MODE_EAX, nonce=nonce)\
                  .encrypt_and_digest(msg)
    serialized_msgctx = nonce + tag + ctx

    # In case pks are serialized, convert them to ecc keys
    for k, v in pk_dict.items():
        if not isinstance(v, ECC.EccKey):
            pk_dict[k] = ECC.import_key(v)
    # Now encrypt the key with pks in pk_dict
    assert len(pk_dict) > 0
    assert len(set((pk.curve for pk in pk_dict.values()))) == 1
    sample_pk = pk_dict.values()[0]
    rand_point = ECC.generate(curve=sample_pk.curve)

    # It is always 161 bytes, extra few bytes in case we run into issues
    serialized_rand_point = serialize_pub_key(rand_point.public_key())

    def _encrypt_w_one_pk(pk):
        if isinstance(pk, basestring):
            pk = ECC.import_key(pk)
        new_point = pk.pointQ * rand_point.d
        ki = hash256(str(new_point.x), str(new_point.y))
        return aes1block(ki, aes_k, op='encrypt')  # iv = 32 '0'-s

    # Hash the ids and take first four bytes, just in case ids are too big.
    # CAUTION: this is valid only if the size of pk_dict is <= 65536
    pkctx = {
        hash256(unicode(_id))[:4]: _encrypt_w_one_pk(pk)
        for _id, pk in pk_dict.items()
    }
    assert all(map(lambda v: len(v) == 32, pkctx.values()))
    serialized_pkctx = ''.join(k + v for k, v in pkctx.items())

    # each id|pkctx is 36 bytes
    assert len(serialized_pkctx) == 36 * len(pk_dict)
    assert len(serialized_rand_point) == 170

    # CTX-format:
    #   2     4    32     4    32           4     32        170         32    32   var
    # <npks><id1><pkctx1><id2><pkctx2>....<idn><pkctxn><rand_point_pk><nonce><tag><ctx>
    return struct.pack('<I', len(pk_dict)) + \
        serialized_pkctx + \
        serialized_rand_point + \
        serialized_msgctx
コード例 #34
0
def setKeys():
    global keys

    with open("keys/ca_pub_key_ECC.pem", "r") as f:
        keys["CA_pub"] = ECC.import_key(f.read())

    keys["priv"] = ECC.generate(curve="p256")
    keys["pub"] = keys["priv"].public_key()
コード例 #35
0
ファイル: pwcryptolib.py プロジェクト: rchatterjee/pam-typopw
 def generate_from_pw(pw, salt, curve='P-256'):
     """Generates a ECC key pair using the randomness derived from pw, salt. 
     """
     rand_seed = PBKDF2(pw, salt, dkLen=16, count=HASH_CNT)
     rand_num_generator = RandomWSeed(rand_seed, 1024)
     return ECC.generate(
         curve=curve, 
         randfunc=rand_num_generator.get_random_bytes
     )
コード例 #36
0
def test_compute_id_w_saltctx():
    pwtypo = 'asdfadsfadf'
    list_keys = {
        i: ECC.generate(curve='P-256')
        for i in xrange(10)
    }
    pk_dict = {k: v.public_key() for k,v in list_keys.items()}
    salt = os.urandom(32)
    saltctx = encrypt(pk_dict, salt)
    id1 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    id2 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    assert isinstance(id1, int)
    assert id1 == id2
コード例 #37
0
def test_functionality():
    # generate a set of pk,sk pairs
    list_keys = {
        i: ECC.generate(curve='P-256')
        for i in xrange(10)
    }
    pk_dict = {k: v.public_key() for k,v in list_keys.items()}
    msg = 'HI Multiuser! in (test_functionality)'
    ctx = encrypt(pk_dict, msg)
    while list_keys:
        sk_dict = dict([list_keys.popitem()])
        _msg = decrypt(sk_dict, ctx)
        assert msg == _msg, "\n_msg={}\n msg={}\n".format(_msg, msg)
コード例 #38
0
ファイル: wallet.py プロジェクト: Nurraku/ABC
def get_private_key():
    """
    Set the private key from a file or by creating a new one
    :return: ECC private key object
    """
    ensure_data_dir()  # ensure directory exists
    try:  # get existing private key
        key = ECC.import_key(open(_PRIVATE_KEY_PATH, 'rt').read())
    except FileNotFoundError:  # create public key
        key = ECC.generate(curve='P-256')
        # write private key to file
        file = open(_PRIVATE_KEY_PATH, 'wt')
        file.write(key.export_key(format='PEM'))
        file.close()

    return key
コード例 #39
0
ファイル: pwcryptolib.py プロジェクト: rchatterjee/pam-typopw
def encrypt_with_ecc(public_ecc_key, message, nonce=None):
    """Takes elliptic curve isntance (public_ecc_key) and a byte string
    (message), and outputs a ciphertext
    """
    assert isinstance(public_ecc_key, ECC.EccKey),\
        "public_ecc_key should be ECC key. Got {}".format(type(public_ecc_key))
    random_ecc_key = ECC.generate(curve=public_ecc_key.curve)
    new_point = public_ecc_key.pointQ * random_ecc_key.d
    h = SHA256.new(str(new_point.x))
    h.update('XXX' + str(new_point.y)) # 'XXX' is a delimiter
    key = h.digest()
    if not nonce:
        nonce = os.urandom(16)
    aes_engine = AES.new(key=key, mode=AES.MODE_EAX, nonce=nonce)
    ctx, tag = aes_engine.encrypt_and_digest(message)
    # Return: <ephemeral_pub_key>, <nonce>, <ciphertext>, <tag>
    return (random_ecc_key.public_key().export_key(format='OpenSSH'),
            aes_engine.nonce, ctx, tag)
コード例 #40
0
ファイル: pwcryptolib.py プロジェクト: rchatterjee/pam-typopw
 def generate(pwhash, curve='secp256r1'):
     rand_num_generator = RandomWSeed(pwhash, 1024)
     return ECC.generate(
         curve=curve, 
         randfunc=rand_num_generator.get_random_bytes
     )
コード例 #41
0
def generate_key_pair():
    private_key = ECC.generate(curve='P-256')
    public_key = private_key.public_key()
    return public_key, private_key