def main(): """The first argument AF_INET is the address domain of the socket. This is used when we have an Internet Domain with any two hosts The second argument is the type of socket. SOCK_STREAM means that data or characters are read in a continuous flow.""" global key_fragment_arr config.set_default_curve() init_ids() #queue containing the available ids key_fragment_arr = key_frag_map(NUM_CLIENTS) server = socket(AF_INET, SOCK_STREAM) server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # checks whether sufficient arguments have been provided if len(sys.argv) != 3: print("Correct usage: script, IP address, port number") exit() # takes the first argument from command prompt as IP address IP_address = str(sys.argv[1]) # takes second argument from command prompt as port number Port = int(sys.argv[2]) """ binds the server to an entered IP address and at the specified port number. The client must be aware of these parameters """ server.bind((IP_address, Port)) """ listens for 100 active connections. This number can be increased as per convenience. """ server.listen(NUM_CLIENTS) while True: """Accepts a connection request and stores two parameters, conn which is a socket object for that user, and addr which contains the IP address of the client that just connected""" conn, addr = server.accept() """Maintains a list of clients for ease of broadcasting a message to all available people in the chatroom""" list_of_clients.append(conn) # prints the address of the user that just connected print(addr[0] + " connected") # creates and individual thread for every user # that connects Thread(target=clientthread,args=(conn,addr)).start() conn.close() server.close()
def __init__(self, host, port): self.host = host self.port = port self.connected_clients = [] self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO set_default_curve() self.alices_private_key = keys.UmbralPrivateKey.from_bytes( b'\x86(\xb4Av\xa7\xf8\x1a\x16\x08\xc0K3\xa8\x1a;"i\xa8\x13Q\xc4s\xe5\x19\xef\x86@\x011\xf7\xfd' ) self.alices_public_key = keys.UmbralPublicKey.from_bytes( b'\x03\xb6\x81\xba\x8e\xcb\x08e\x7f(\x04\xe3\xff\xbe\xc6UA\xa0\xfe5\x1c\xb2\xe0\xf0\xf7;\xd1D}NHo\xf7' ) self.alices_signing_key = keys.UmbralPrivateKey.from_bytes( b'Q:5|\x01^=\xd6D\xbd\xed\xbb\x8f\xef\xc9\x04\xed2g}\xf3Yn\xf4\xb2\xfdZ\x03\x16\xceM\x94' ) self.alices_verifying_key = keys.UmbralPublicKey.from_bytes( b'\x03Yn\x9dx\xa7\x1c\xd1\xad\xe5\x80\xc9[\xe8^\xae\x81\x95\xaaQ\xadi\x9d\x83\x91\x18}\xc2\x85\xe3\x1em\xd0' ) self.alices_signer = signing.Signer( private_key=self.alices_signing_key) try: self._db_connect() except BaseException: log_info("Unable to connect database")
def test_register_request(): config.set_default_curve() #Create private and public keys priv_key = keys.UmbralPrivateKey.gen_key() pub_key = priv_key.get_pubkey() #Serialize the public key pk_bytes = pub_key.to_bytes() pub_key_test = keys.UmbralPublicKey.from_bytes(pk_bytes) assert (pub_key_test.point_key == pub_key.point_key ) #Test umbral to, from bytes my_req = Request.register_request(pub_key) my_req_serialized = my_req.serialize() new_req = Request.deserialize(my_req_serialized) print(my_req.serialize()) print(new_req.serialize()) assert (new_req.serialize() == my_req.serialize()) #Create the public key objects from the bytes in the request arguments pub_key_1 = keys.UmbralPublicKey.from_bytes(new_req.args['pub_key']) pub_key_2 = keys.UmbralPublicKey.from_bytes(my_req.args['pub_key']) assert (pub_key_1.point_key == pub_key_2.point_key) print('SUCCESS')
def main(m, n, filenames): files = [open(filename, 'w') for filename in filenames] config.set_default_curve() alice_privkey = keys.UmbralPrivateKey.gen_key() alice_pubkey = alice_privkey.get_pubkey() bob_privkey = keys.UmbralPrivateKey.gen_key() bob_pubkey = bob_privkey.get_pubkey() mock_kms = MockNetwork() sys.stderr.write('Server with PID %s is ready to pipe messages.\n' % os.getpid()) for line in sys.stdin: ciphertext, capsule = pre.encrypt(alice_pubkey, line.rstrip('\n').encode('utf8')) alice_kfrags = pre.split_rekey(alice_privkey, bob_pubkey, m, n) policy_id = mock_kms.grant(alice_kfrags) bob_cfrags = mock_kms.reencrypt(policy_id, capsule, m) bob_capsule = capsule for cfrag in bob_cfrags: bob_capsule.attach_cfrag(cfrag) decrypted = pre.decrypt(ciphertext, bob_capsule, bob_privkey, alice_pubkey) for file in files: file.write('%s\n' % decrypted.decode('utf8')) file.flush() mock_kms.revoke(policy_id)
def key_gen(): ''' Generate a key pair for the current client under the default choice of Eliptic Curve. ''' config.set_default_curve() priv_key = keys.UmbralPrivateKey.gen_key() pub_key = priv_key.get_pubkey() return (priv_key, pub_key)
def main(): config.set_default_curve() secret = CurveBN.gen_rand() shares = share_secret(secret, 3, 6) print(secret.to_bytes()) recovered_secret = recover_secret(shares[:3]) print(recovered_secret.to_bytes())
def serve(): config.set_default_curve() server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) rpc_pb2_grpc.add_ReProxyServicer_to_server(ReProxy(), server) server.add_insecure_port('[::]:50052') server.start() print("Nucypher server start :50052") try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0)
def get_instance(self): if not self._unique_instance: set_default_curve() self.bb = BulletinBoard.get_instance() self.proxy = Proxy.get_instance() self.private_key = UmbralPrivateKey.gen_key() self.public_key = self.private_key.get_pubkey() self.singning_key = UmbralPrivateKey.gen_key() self.verifying_key = self.singning_key.get_pubkey() self.signer = Signer(private_key=self.singning_key) self.voters = [] self._unique_instance = self.__internal_new__() return self._unique_instance
def setup(): global config config = uconfig.set_default_curve() global mock_kms mock_kms = MockNetwork() global api api = ipfsapi.connect('127.0.0.1', 5001)
def __init__(self, host, port): self.host = host self.port = port self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) set_default_curve() self.bobs_private_key = keys.UmbralPrivateKey.gen_key() self.bobs_public_key = self.bobs_private_key.get_pubkey() #self.bobs_private_key = keys.UmbralPrivateKey.from_bytes( # b'"\xf7~\xb994\x1a\xe0b\x96.\'m\xa6<S\x06L\xb7\xb2\xf6a\x88^\xd3\xd6\xae!\xc7S^\xba') #self.bobs_public_key = keys.UmbralPublicKey.from_bytes( # b'\x03\xcfy\xd3\xbb\xf6\x9e\x9e\x82\xf6+c\xcar\xdc\xf2QaM\xc1\xf2h\xfdg\xdc\x16\xd0\xb4oA\xdc\x92\xdc') self.alices_public_key = keys.UmbralPublicKey.from_bytes( b'\x03\xb6\x81\xba\x8e\xcb\x08e\x7f(\x04\xe3\xff\xbe\xc6UA\xa0\xfe5\x1c\xb2\xe0\xf0\xf7;\xd1D}NHo\xf7') self.alices_verifying_key = keys.UmbralPublicKey.from_bytes( b'\x03Yn\x9dx\xa7\x1c\xd1\xad\xe5\x80\xc9[\xe8^\xae\x81\x95\xaaQ\xadi\x9d\x83\x91\x18}\xc2\x85\xe3\x1em\xd0')
def setup(): # Setup pyUmbral global config config = uconfig.set_default_curve() global mock_kms mock_kms = MockNetwork() global r r = redis.Redis(host='localhost', port=6379, db=0)
def setup(): # Setup pyUmbral global config config = uconfig.set_default_curve() global mock_kms mock_kms = MockNetwork() global bob_privkey bob_privkey = keys.UmbralPrivateKey.gen_key() global bob_pubkey bob_pubkey = bob_privkey.get_pubkey()
import pytest from collections import namedtuple from cryptography.hazmat.primitives.asymmetric import ec from umbral import keys from umbral.curvebn import CurveBN from umbral.config import set_default_curve from umbral.point import Point set_default_curve(ec.SECP256K1) MockKeyPair = namedtuple('TestKeyPair', 'priv pub') parameters = [ # (N, M) (1, 1), (6, 1), (6, 4), (6, 6), (50, 30) ] @pytest.fixture(scope='function') def alices_keys(): priv = keys.UmbralPrivateKey.gen_key() pub = priv.get_pubkey() return MockKeyPair(priv, pub) @pytest.fixture(scope='function')
from umbral import config config.set_default_curve()
You should have received a copy of the GNU General Public License along with pyUmbral. If not, see <https://www.gnu.org/licenses/>. """ import pytest from collections import namedtuple from umbral import keys from umbral.curve import SECP256K1, SECP384R1, SECP256R1 from umbral.curvebn import CurveBN from umbral.config import set_default_curve from umbral.point import Point from umbral.signing import Signer from umbral import pre set_default_curve(SECP256K1) parameters = ( # (N, M) (1, 1), (6, 1), (6, 4), (6, 6), (50, 30) ) wrong_parameters = ( # (N, M) (-1, -1), (-1, 0), (-1, 5), (0, -1), (0, 0), (0, 5), (1, -1), (1, 0), (1, 5),
import umbral from umbral import config from umbral.curve import SECP256K1 config.set_default_curve(SECP256K1) from umbral import keys, signing from umbral import pre from umbral.kfrags import KFrag import os from dotenv import load_dotenv import pickle import marshal import json project_folder = os.getcwd() load_dotenv(os.path.join(project_folder, '.env')) private_key_byte = pickle.load( open('keys/' + os.getenv("WALLET") + '/private_key.pem', 'rb')) private_key = keys.UmbralPrivateKey.from_bytes(private_key_byte) signing_key_byte = pickle.load( open('keys/' + os.getenv("WALLET") + '/signing_key.pem', 'rb')) signing_key = keys.UmbralPrivateKey.from_bytes(signing_key_byte) Signer = signing.Signer(private_key=signing_key) public_key_byte = pickle.load(open(os.getenv("PK_PATH"), 'rb')) public_key = keys.UmbralPublicKey.from_bytes(public_key_byte)
mode = 'w' if generate_again else 'x' try: with open(path, mode) as f: json.dump(vector, f, indent=2) except FileExistsError: pass # If True, this will overwrite existing test vector files with new randomly generated instances generate_again = False ######### # SETUP # ######### set_default_curve() params = default_params() curve = params.curve # We create also some Umbral objects for later delegating_privkey = UmbralPrivateKey.gen_key(params=params) receiving_privkey = UmbralPrivateKey.gen_key(params=params) signing_privkey = UmbralPrivateKey.gen_key(params=params) verifying_key = signing_privkey.get_pubkey() delegating_key = delegating_privkey.get_pubkey() receiving_key = receiving_privkey.get_pubkey() signer = Signer(signing_privkey) kfrags = pre.generate_kfrags(delegating_privkey=delegating_privkey,
def init(): config.set_default_curve(SECP256K1)
#/usr/bin/env python #-*- coding:utf-8 -*- from web3 import Web3, HTTPProvider import ipfshttpclient from cryptography import fernet#用于对称加密 from umbral import pre,keys,signing,config,params,kfrags,cfrags import os from socket import * import pickle from hexbytes import HexBytes import requests import json import threading config.set_default_curve()#设置非加密方式,默认secp256k1 THRESHOLD=2#default threshold number SPLIT_NUMBER=2#default split_frag number class ETHConnectionError(Exception): def __init__(self,message): self.msg=message def __str__(self): print("APIConnection Error:",self.msg) #信息包结构 class info_packet(): def __init__(self,capsule=None,pub_key1=None,pub_key2=None,verify_key=None,tx_hash=None,kfrag=None,cfrag=None,IP=None,selfport=None,check=None): self.info={"capsule":capsule, "pub_key1":pub_key1, "pub_key2":pub_key2, "verify_key":verify_key, "tx_hash":tx_hash, "kfrag":kfrag,
def test_recepient_add_records_set(self): #Generate keys config.set_default_curve(SECP256K1) patient_private_key = keys.UmbralPrivateKey.gen_key() patient_public_key = patient_private_key.get_pubkey() recepient_private_key = keys.UmbralPrivateKey.gen_key() recepient_public_key = recepient_private_key.get_pubkey() recepient_signing_key = keys.UmbralPrivateKey.gen_key() recepient_verifying_key = recepient_signing_key.get_pubkey() recepient_signer = signing.Signer(private_key=recepient_signing_key) #Convert keys to hex hexed_patient_public_key = patient_public_key.to_bytes().hex() hexed_recepient_public_key = recepient_public_key.to_bytes().hex() hexed_recepient_verifying_key = recepient_verifying_key.to_bytes().hex() #Signup patient data = { 'first_name': 'Gordo', 'last_name': 'Freema', 'email': '*****@*****.**', 'password': '******', 'eth_address': '0x73015966604928A312F79F7E69291a656Cb88603', 'pub_key': hexed_patient_public_key } response = self.client.post('/patients/signup/', data) #Signup recepient data = { 'organisation_id': 'someseriousorganisationidentifier', 'first_name': 'Gordon', 'last_name': 'Freeman', 'email': '*****@*****.**', 'password': '******', 'eth_address': '0x73015966604928A312F79F7E69291a656Cb88603', 'pub_key': hexed_recepient_public_key } response = self.client.post('/recepients/signup/', data) #Log in as patient self.client.login(username='******', password='******') data = { 'patient_id': 2, 'recepient_id': 2 } #Delegate add records permission to recepient response = self.client.post('/patients/delegations/make/', data) #Log in as recepient self.client.login(username='******', password='******') #Encrypt message plaintext = b'Proxy Re-encryption is cool!' ciphertext, capsule = pre.encrypt(recepient_public_key, plaintext) kfrags = pre.generate_kfrags(delegating_privkey=recepient_private_key, signer=recepient_signer, receiving_pubkey=patient_public_key, threshold=10, N=20) #Add encrypted record data = { 'patient_id': 2, 'type': 'type', 'data': ciphertext.hex(), 'capsule': capsule.to_bytes().hex() } response = self.client.post('/records/add/', data) self.assertEqual(response.status_code, 201) #Add kfrags for kfrag in kfrags: data = { 'delegation_id': 1, 'bytes': kfrag.to_bytes().hex() } self.client.post('/patients/kfrags/', data) #Add verifying_key data = { 'records_set_id': 1, 'recepient_id': 3, 'verifying_key': hexed_recepient_verifying_key } response = self.client.post('/re_encryptions/', data) #Login as patient self.client.login(username='******', password='******') response = self.client.get('/me/records/') from_proxy_capsule = bytes.fromhex(response.data[0]['capsule']) from_proxy_data = bytes.fromhex(response.data[0]['data']) umbral_parameteres = UmbralParameters(SECP256K1) from_proxy_capsule = pre.Capsule.from_bytes( from_proxy_capsule, umbral_parameteres ) response = self.client.get('/patients/kfrags/') """ Patient can receive kfrags for each re_encryption """ from_proxy_kfrags = [KFrag.from_bytes(bytes.fromhex(kfrag['bytes'])) for kfrag in response.data] response = self.client.get('/re_encryptions/1/') from_proxy_verifying_key = bytes.fromhex(response.data['verifying_key']) """ Patient gets verifying_key """ from_proxy_verifying_key = keys.UmbralPublicKey.from_bytes( from_proxy_verifying_key, params=umbral_parameteres ) from_proxy_capsule.set_correctness_keys( delegating=recepient_public_key, receiving=patient_public_key, verifying=from_proxy_verifying_key ) for kfrag in from_proxy_kfrags: cfrag = pre.reencrypt(kfrag, from_proxy_capsule) from_proxy_capsule.attach_cfrag(cfrag) cleartext = pre.decrypt( ciphertext=from_proxy_data, capsule=from_proxy_capsule, decrypting_key=patient_private_key ) """ Patient opens the capsule to decrypt records organisation added. Then patient can reencrypt whole records to delegate editing and reading permissions to other organisations """ self.assertEqual(cleartext, plaintext)