def decrypt(): # Get data from request json_data = json.loads(request.data.decode('utf-8')) ciphertext, policy_id, capsule, alice_pubkey, alice_signing_pubkey = json_data[ 'ciphertext'], json_data['policy_id'], json_data['capsule'], json_data[ 'alice_pubkey'], json_data['alice_signing_pubkey'] # convert to bytes ciphertext = string_to_bytes(ciphertext) capsule = string_to_bytes(capsule) capsule = pre.Capsule.from_bytes(capsule, params.UmbralParameters(SECP256K1)) alice_pubkey = string_to_bytes(alice_pubkey) alice_pubkey = keys.UmbralPublicKey.from_bytes(alice_pubkey) alice_signing_pubkey = string_to_bytes(alice_signing_pubkey) alice_signing_pubkey = keys.UmbralPublicKey.from_bytes( alice_signing_pubkey) # Perform re-encryption request bob_cfrags = mock_kms.reencrypt(policy_id, capsule, 10) # Simulate capsule handoff, and set the correctness keys. # Correctness keys are used to prove that a cfrag is correct and not modified # by a proxy node in the network. They must be set to use the `decrypt` and # `attach_cfrag` funtions. bob_capsule = capsule bob_capsule.set_correctness_keys(alice_pubkey, bob_pubkey, alice_signing_pubkey) for cfrag in bob_cfrags: bob_capsule.attach_cfrag(cfrag) decrypted_data = pre.decrypt(ciphertext, bob_capsule, bob_privkey, alice_signing_pubkey) return jsonify({ "decrypted_data": decrypted_data.decode('utf-8'), })
def __init__(self,eth_api,ipfs_api): self.w3 = Web3(HTTPProvider(eth_api))#以太坊geth客户端接口 #print(self.w3) if not self.w3.isConnected(): raise ETHConnectionError("区块链未连接") self.client = ipfshttpclient.connect(ipfs_api)#ipfs接口 self.port=7001#数据帧接收端口 self.record={} #json 文件加载 if os.path.exists("data.pkl"): param=params.UmbralParameters(self.curve) with open("data.pkl","rb") as f: records=pickle.load(f) for record in records: #record也许需要处理一下 for key in record.keys(): capsule=pre.Capsule.from_bytes(record[key],param) record[key]=capsule self.record.update(record) print("Already get record:",self.record) self.tempo_cfrags={}#暂时接收来自其他节点的cfrag帧 sock_ip_get = socket(AF_INET, SOCK_DGRAM) sock_ip_get.connect(('8.8.8.8', 80)) ip = sock_ip_get.getsockname()[0] self.IP=ip print("Host Information:",self.IP,":",self.port)
def getKey(self, keyName, path): key = self.contract.call().keys(keyName) keyExist = key[4] if keyExist: curveVar = umbral.config.default_curve() paramsVar = params.UmbralParameters(curveVar) capsule = pre.Capsule.from_bytes(key[1], paramsVar) valueBytes = key[0] value = None try: value = self._decrypt(valueBytes, capsule) except: try: owner = keys.UmbralPublicKey.from_bytes(key[2]) keyName = keyName.decode('utf-8') with open(path + '/' + keyName + '.s', 'rb') as signatureFile: signature = signatureFile.read() signature = keys.UmbralPublicKey.from_bytes(signature) capsule.set_correctness_keys( delegating = owner, receiving = self.publicKey, verifying = signature ) with open(path + '/' + keyName + '.f', 'rb') as cfragFile: cfragsBytes = cfragFile.read() cfrag = fragments.CapsuleFrag.from_bytes(cfragsBytes) capsule.attach_cfrag(cfrag) value = self._decrypt(valueBytes, capsule) except Exception as e: print(e) finally: if value is not None: print(value) else: print('Key is not exist')
def decrypt(): if request.method == 'POST': # Get the private key bobPrivKey = string_to_bytes(request.form["bobPrivKey"]) bobPrivKey = keys.UmbralPrivateKey.from_bytes(bobPrivKey) bobPubKey = bobPrivKey.get_pubkey() # read the capsule from the json dump with open('data.json') as json_file: data1 = json.load(json_file) ciphertext = string_to_bytes(data1['ciphertext']) capsule = string_to_bytes(data1['capsule']) capsule = pre.Capsule.from_bytes( capsule, params.UmbralParameters(SECP256K1)) # get the kfrags with open('hospital.json') as json_file: data2 = json.load(json_file) # kfrags = data2['kfrags'] alicePubKey = string_to_bytes(data2["alicePubKey"]) alicePubKey = keys.UmbralPublicKey.from_bytes(alicePubKey) alice_verifying_key = string_to_bytes(data2["alice_verifying_key"]) alice_verifying_key = keys.UmbralPublicKey.from_bytes( alice_verifying_key) global kfrags kfrags = random.sample(kfrags, 10) capsule.set_correctness_keys(delegating=alicePubKey, receiving=bobPubKey, verifying=alice_verifying_key) cfrags = list() for kfrag in kfrags: cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule) cfrags.append(cfrag) capsule.set_correctness_keys(delegating=alicePubKey, receiving=bobPubKey, verifying=alice_verifying_key) for cfrag in cfrags: capsule.attach_cfrag(cfrag) #decrypt the data plainBobtext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=bobPrivKey) plainBobtext = plainBobtext.decode('utf-8') return render_template('decrypt.html', plainBobtext=plainBobtext, data=data1) with open('data.json') as json_file: data1 = json.load(json_file) return render_template('decrypt.html', data=data1)
def __init__(self, ipfs_api, leval): self.client = ipfshttpclient.connect(ipfs_api) # Connection with the IPFS HTTP-Interface self.port = 7001 # The task-receiving port self.record = {} # the capsule with the CID # load the json file if os.path.exists("data.pkl"): param = params.UmbralParameters(self.curve) with open("data.pkl", "rb") as f: records = pickle.load(f) for record in records: for key in record.keys(): capsule = pre.Capsule.from_bytes(record[key], param) record[key] = capsule self.record.update(record) print("Already get record:", self.record) # Receiving cfrag from other node self.tempo_cfrags = {} #Get the local IP sock_ip_get = socket(AF_INET, SOCK_DGRAM) sock_ip_get.connect(('8.8.8.8', 80)) ip = sock_ip_get.getsockname()[0] self.IP = ip print("Host Information:", self.IP, ":", self.port) #the task queue self.task_queue = PriorityQueue() #the load state of the neighbor node self.neighbor_state = defaultdict(list) self.state = stat_packet(id=self.client.id()['ID'], To=20, Tu=10, state=0) self.leval = leval self.index = 0 self.lock = threading.Lock() self.lock2 = threading.Lock() self.lock3 = threading.Lock() self.local = threading.local() self.time_dict = defaultdict(float) self.update_flag = 0 self.old_version = set() self.handled_kfrag_number = 0 self.time_stat1 = None self.time_stat2 = None self.finish_files = 0
def __init__(self, privateKey=None): # umbral.config.set_default_curve() self.ehr = EHR() curveVar = curve.Curve(714) paramsVar = params.UmbralParameters(curveVar) if privateKey is None: self.privateKey = keys.UmbralPrivateKey.gen_key(params=paramsVar) self.privateKeyBytes = self.privateKey.to_bytes() else: self.privateKeyBytes = privateKey self.privateKey = keys.UmbralPrivateKey.from_bytes( key_bytes=self.privateKeyBytes) self.publicKey = self.privateKey.get_pubkey()
def share(self, keyName, path, publicKeyFileName): key = self.contract.call().keys(keyName) keyExist = key[4] if keyExist: try: with open(path + '/' + publicKeyFileName + '.k', 'rb') as publicKeyFile: publicKeyBytes = publicKeyFile.read() except Exception as e: print(e) else: try: publicKey = keys.UmbralPublicKey.from_bytes(publicKeyBytes) signingPrivateKey = keys.UmbralPrivateKey.gen_key() signer = signing.Signer(private_key = signingPrivateKey) kfrags = pre.generate_kfrags( delegating_privkey = self.privateKey, signer = signer, receiving_pubkey = publicKey, threshold = 1, N = 1 ) directory = path + '/' + publicKeyFileName + '/' if not os.path.exists(directory): os.makedirs(directory) curveVar = umbral.config.default_curve() paramsVar = params.UmbralParameters(curveVar) capsule = pre.Capsule.from_bytes(key[1], paramsVar) signingPublicKey = signingPrivateKey.get_pubkey() capsule.set_correctness_keys( delegating = self.publicKey, receiving = publicKey, verifying = signingPublicKey ) for kfrag in kfrags: cfrag = pre.reencrypt( kfrag = kfrag, capsule = capsule ) cfrag = cfrag.to_bytes() keyName = keyName.decode('utf-8') with open(directory + keyName + '.f', 'wb') as cfragFile: cfragFile.write(cfrag) signingPublicKeyBytes = signingPublicKey.to_bytes() with open(directory + keyName + '.s', 'wb') as signatureFile: signatureFile.write(signingPublicKeyBytes) except Exception as e: print(e) else: print('Done') else: print('Key is not exist')
def decryptUploaded(): json_data = json.loads(request.data.decode('utf-8')) capsule = json_data['capsule'] cipherText = json_data['cipherText'] alices_private_key = json_data['alices_private_key'] ciphertext = string_to_bytes(cipherText) capsule = string_to_bytes(capsule) capsule = pre.Capsule.from_bytes(capsule, params.UmbralParameters(SECP256K1)) alices_private_key = keys.UmbralPrivateKey.from_bytes( string_to_bytes(alices_private_key)) cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=alices_private_key) json_my_list = json.dumps(cleartext.decode('utf-8')) return json_my_list
def decrypt(): # Get data from request json_data = json.loads(request.data.decode('utf-8')) # json_data = json.loads("{ \"alice_pubkey\": \"AvTifaAfuL1dTwGbDiBDmBiVRS7TCbNeDkrqKPesjTK6\", \"alice_signing_pubkey\": \"AmopleZUj7aSYA8M9sZGdRGwTMrUbVKUo5B36JXbD1\", \"ciphertext\": \"LZN+p4DkpYo6nfXOLTMVO9rGKq00s9wVba27ydvjFF+jFjmNBC0dD29N5Irq\",\"ipfsHash\": \"QmS95HoTiDTTydAvCT9W3t7VHnip17T24DPZN5J6KkyLCa\", \"policy_id\": \"a0228680-6bd9-4b2c-9669-bd0239c60c1f\"}") ciphertext, policy_id, ifpsHash, alice_pubkey, alice_signing_pubkey, readers_pubkey = json_data["ciphertext"], json_data["policy_id"], json_data["ipfsHash"], json_data["alice_pubkey"], json_data["alice_signing_pubkey"], json_data["readers_pubkey"] # ciphertext, policy_id, ifpsHash, alice_pubkey, alice_signing_pubkey = json_data["ciphertext"], json_data["policy_id"], json_data["ipfsHash"], json_data["alice_pubkey"], json_data["alice_signing_pubkey"] # convert to bytes ciphertext = string_to_bytes(ciphertext) capsule = string_to_bytes(api.get_json(ifpsHash)) capsule = pre.Capsule.from_bytes(capsule, params.UmbralParameters(SECP256K1)) alice_pubkey = string_to_bytes(alice_pubkey) alice_pubkey = keys.UmbralPublicKey.from_bytes(alice_pubkey) alice_signing_pubkey = string_to_bytes(alice_signing_pubkey) alice_signing_pubkey = keys.UmbralPublicKey.from_bytes(alice_signing_pubkey) readers_pubkey = string_to_bytes(readers_pubkey) readers_pubkey = keys.UmbralPublicKey.from_bytes(readers_pubkey) # Perform re-encryption request try: reciever_cfrags = mock_kms.reencrypt(policy_id, capsule, 10) except: # Failed to decrypt then return jsonify({ "status": "could not decrypt", }) # Simulate capsule handoff, and set the correctness keys. # Correctness keys are used to prove that a cfrag is correct and not modified # by a proxy node in the network. They must be set to use the `decrypt` and # `attach_cfrag` funtions. reciever_capsule = capsule # readers_privkey = bob_privkey # readers_pubkey = alice_pubkey reciever_capsule.set_correctness_keys(alice_pubkey, readers_pubkey, alice_signing_pubkey) for cfrag in reciever_cfrags: reciever_capsule.attach_cfrag(cfrag) decrypted_data = pre.decrypt(ciphertext, reciever_capsule, readers_privkey) decrypted_data = decrypted_data.decode('utf-8') return jsonify({ "decrypted_data": decrypted_data, })
def getUser(self, userAddress): userAddress = Web3.toChecksumAddress(userAddress) user = self.ehr.getUser(userAddress) curveVar = curve.Curve(714) paramsVar = params.UmbralParameters(curveVar) firstNameCapsule = pre.Capsule.from_bytes(user[0], paramsVar) lastNameCapsule = pre.Capsule.from_bytes(user[1], paramsVar) dateOfBirthCapsule = pre.Capsule.from_bytes(user[2], paramsVar) firstName = pre.decrypt(ciphertext=user[3], capsule=firstNameCapsule, decrypting_key=self.privateKey) lastName = pre.decrypt(ciphertext=user[4], capsule=lastNameCapsule, decrypting_key=self.privateKey) dateOfBirth = pre.decrypt(ciphertext=user[5], capsule=dateOfBirthCapsule, decrypting_key=self.privateKey) firstName = firstName.decode('utf-8') lastName = lastName.decode('utf-8') dateOfBirth = dateOfBirth.decode('utf-8') return firstName, lastName, dateOfBirth
def getAllDiseases(self, userAddress): userAddress = Web3.toChecksumAddress(userAddress) diseasesTimestamps = self.getDiseasesTimestamps(userAddress) curveVar = curve.Curve(714) paramsVar = params.UmbralParameters(curveVar) diseases = [] for diseaseTimestamp in diseasesTimestamps: disease = self.ehr.getDisease(userAddress, diseaseTimestamp) diagnosisCapsule = pre.Capsule.from_bytes(disease[3], paramsVar) therapyCapsule = pre.Capsule.from_bytes(disease[4], paramsVar) diagnosis = pre.decrypt(ciphertext=disease[5], capsule=diagnosisCapsule, decrypting_key=self.privateKey) therapy = pre.decrypt(ciphertext=disease[6], capsule=therapyCapsule, decrypting_key=self.privateKey) diseaseEncrypted = { 'diagnosis': diagnosis.decode('utf-8'), 'therapy': therapy.decode('utf-8') } diseases.append(diseaseEncrypted) return diseases
def decryptDelegated(): json_data = json.loads(request.data.decode('utf-8')) alices_public_key = json_data['alices_public_key'] alices_verifying_key = json_data['alices_verifying_key'] bobs_public_key = json_data['bobs_public_key'] bobs_private_key = json_data['bobs_private_key'] capsule = json_data['capsule'] cipherText = json_data['cipherText'] policyId = json_data['policyId'] alices_public_key = string_to_bytes(alices_public_key) alices_public_key = keys.UmbralPublicKey.from_bytes(alices_public_key) alices_verifying_key = string_to_bytes(alices_verifying_key) alices_verifying_key = keys.UmbralPublicKey.from_bytes( alices_verifying_key) bobs_public_key = string_to_bytes(bobs_public_key) bobs_public_key = keys.UmbralPublicKey.from_bytes(bobs_public_key) bobs_private_key = keys.UmbralPrivateKey.from_bytes( string_to_bytes(bobs_private_key)) capsule = string_to_bytes(capsule) capsule = pre.Capsule.from_bytes(capsule, params.UmbralParameters(SECP256K1)) kfrags = kfrags_array[policyId] ciphertext = string_to_bytes(cipherText) capsule.set_correctness_keys(delegating=alices_public_key, receiving=bobs_public_key, verifying=alices_verifying_key) cfrags = list() for fragment in kfrags[:3]: cfrag = pre.reencrypt(fragment, capsule=capsule) cfrags.append(cfrag) for cfrag in cfrags: capsule.attach_cfrag(cfrag) bob_cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=bobs_private_key) json_my_list = json.dumps(bob_cleartext.decode('utf-8')) return json_my_list
apk_hex = alices_public_key.to_bytes().hex() bpk_hex = bobs_public_key.to_bytes().hex() vpk_hex = alices_verifying_key.to_bytes().hex() #pprint(bob_capsule) #pprint("))))))))))))))))capsule_from_file") capsule_from_file_bytes = bob_capsule.to_bytes() capsule_from_file_hex = bob_capsule.to_bytes().hex() t = json.dumps({ 'delegating': apk_hex, 'receiving': bpk_hex, 'verifying': vpk_hex, 'capsule': capsule_from_file_hex }) curve = config.default_curve() params = params.UmbralParameters(curve=curve) # params = default_params() #params = pre.Capsule.params #params = pre.Capsule.params capsule_from_server = pre.Capsule.from_bytes( bytes.fromhex(capsule_from_file_hex), params=params) #assert capsule_from_server == bob_capsule bob_cleartext = pre.decrypt(ciphertext=ciphertext_from_file, capsule=capsule_from_server, decrypting_key=bobs_private_key) ## print("bob_cleartext") ## print(bob_cleartext) image = Image.open(io.BytesIO(bob_cleartext)) image.save("python/proxy/35.jpg") pprint(t)
def worker(self): while True: if (self.task_queue.empty()): print("Waiting...........") time.sleep(0.3) continue #obj=self.task_queue.get(block=True) self.lock.acquire() #old_value=self.task_queue.qsize() obj = self.task_queue.get(block=True) print("get a task") if (self.task_queue.qsize() == self.state.info["To"] - 5): self.state.info["state"] = 1 #self.lock.release() ip_id = self.IP_FIND() for ip, id in ip_id.items(): packet = stat_packet(id=self.state.info["id"], To=self.state.info["To"], Tu=self.state.info["Tu"], state=1) self.send(packet, ip) elif (self.task_queue.qsize() == self.state.info["Tu"] - 5): print("Free State") self.state.info['state'] = 0 #self.lock.release() ip_id = self.IP_FIND() for ip, id in ip_id.items(): packet = stat_packet(id=self.state.info["id"], To=self.state.info["To"], Tu=self.state.info["Tu"], state=0) self.send(packet, ip) self.lock.release() time.sleep(0.3) obj = obj[2] kfrag = obj.info["kfrag"] kfrag = kfrags.KFrag.from_bytes(kfrag) capsule = obj.info["capsule"] param = params.UmbralParameters(self.curve) capsule = pre.Capsule.from_bytes(capsule, param) pub_key1 = obj.info["pub_key1"] pub_key1 = keys.UmbralPublicKey.from_bytes(pub_key1) pub_key2 = obj.info["pub_key2"] pub_key2 = keys.UmbralPublicKey.from_bytes(pub_key2) verify_key = obj.info["verify_key"] verify_key = keys.UmbralPublicKey.from_bytes(verify_key) capsule.set_correctness_keys(pub_key2, pub_key1, verify_key) print(capsule) cfrag = pre.reencrypt(kfrag, capsule) print("CFrag finish", cfrag) cfrag = cfrag.to_bytes() cfrag_packet = info_packet(cfrag=cfrag, CID=obj.info["CID"], version=obj.info["version"]) self.send(packet=cfrag_packet, des_IP=obj.info["IP"]) self.handled_kfrag_number += 1 print(self.handled_kfrag_number)
def handle_request(self, obj): #user is pub1,data owner is pub2 if (obj.info["check"] == 0): print("received the request") capsule = self.record[obj.info["CID"]] capsule = capsule.to_bytes() pub_key2 = self.pub_key.to_bytes() verify_key = self.verifying_key.to_bytes() responce = info_packet(capsule=capsule, CID=obj.info["CID"], check=1, IP=self.IP, pub_key2=pub_key2, verify_key=verify_key) self.send(packet=responce, des_IP=obj.info["IP"]) elif (obj.info["check"] == 1): print("receive the response") capsule = obj.info["capsule"] param = params.UmbralParameters(self.curve) capsule = pre.Capsule.from_bytes(capsule, param) pub_key2 = obj.info["pub_key2"] pub_key2 = keys.UmbralPublicKey.from_bytes(pub_key2) verify_key = obj.info["verify_key"] verify_key = keys.UmbralPublicKey.from_bytes(verify_key) capsule.set_correctness_keys(pub_key2, self.pub_key, verify_key) if obj.info["CID"] in self.record: self.record[obj.info["CID"]].append(capsule) else: self.record[obj.info["CID"]] = [capsule] pub_key = self.pub_key.to_bytes() responce = info_packet(CID=obj.info["CID"], IP=self.IP, pub_key1=pub_key, check=2, ttl=0, leval=self.leval) self.send(packet=responce, des_IP=obj.info["IP"]) elif (obj.info["check"] == 2): print("dispatch the kfrag") capsule = self.record[obj.info["CID"]] pub_key1 = keys.UmbralPublicKey.from_bytes(obj.info["pub_key1"]) kfrags_ = pre.generate_kfrags(self.pri_key, pub_key1, THRESHOLD, SPLIT_NUMBER, self.signer) capsule = capsule.to_bytes() pub_key1 = pub_key1.to_bytes() pub_key2 = self.pub_key.to_bytes() verify_key = self.verifying_key.to_bytes() IP_ID = self.IP_FIND() version = hashlib.sha256(str( time.time()).encode("utf-8")).hexdigest() #print(version,obj.info["IP"],obj.info["CID"]) visited_id = deque(maxlen=len(IP_ID)) for kfrag in kfrags_: kfrag = kfrag.to_bytes() flag = 0 for ip, id in IP_ID.items(): if id not in visited_id: if (self.neighbor_state[id][2] == 0 and ip != obj.info["IP"]): packet = info_packet(capsule=capsule, kfrag=kfrag, CID=obj.info["CID"], IP=obj.info["IP"], pub_key1=pub_key1, pub_key2=pub_key2, verify_key=verify_key, check=3, ttl=0, leval=obj.info["leval"], version=version) self.send(packet, ip) visited_id.append(id) if (len(visited_id) == len(IP_ID)): visited_id.clear() flag = 1 break if (flag == 0): for ip, id in IP_ID.items(): if id not in visited_id: if (self.neighbor_state[id][2] == 1 and ip != obj.info["IP"]): packet = info_packet(capsule=capsule, kfrag=kfrag, CID=obj.info["CID"], IP=obj.info["IP"], pub_key1=pub_key1, pub_key2=pub_key2, verify_key=verify_key, check=3, ttl=0, leval=obj.info["leval"], version=version) self.send(packet, ip) visited_id.append(id) if (len(visited_id) == len(IP_ID)): visited_id.clear() flag = 1 break if (flag == 0): for ip, id in IP_ID.items(): if id not in visited_id: if (self.neighbor_state[id][2] == 2 and ip != obj.info["IP"]): packet = info_packet(capsule=capsule, kfrag=kfrag, CID=obj.info["CID"], IP=obj.info["IP"], pub_key1=pub_key1, pub_key2=pub_key2, verify_key=verify_key, check=3, ttl=0, leval=obj.info["leval"], version=version) self.send(packet, ip) visited_id.append(id) if (len(visited_id) == len(IP_ID)): visited_id.clear() flag = 1 break elif (obj.info["check"] == 3): print("get the kfrag") self.lock3.acquire() #time.sleep(0.3) if (self.state.info['state'] == 2): ip_id = self.IP_FIND() flag = 0 random_node = list(ip_id.items()) shuffle(random_node) for ip, id in random_node: if (self.neighbor_state[id][2] == 0 and ip != obj.info["IP"]): #add ttl obj.info["ttl"] += 1 self.send(obj, ip) flag = 1 break if (flag == 0): for ip, id in random_node: if (self.neighbor_state[id][2] == 1 and ip != obj.info["IP"]): #add ttl obj.info["ttl"] += 1 self.send(obj, ip) flag = 1 break if (flag == 0): for ip, id in random_node: if (self.neighbor_state[id][2] == 2 and ip != obj.info["IP"]): #add ttl obj.info["ttl"] += 1 self.send(obj, ip) break else: self.lock.acquire() #old_va=self.task_queue.qsize() temp_list = [] for i in range(self.task_queue.qsize()): a = self.task_queue.get() temp_list.append(a) for i in range(len(temp_list)): temp_list[i][0] -= 1 self.task_queue.put(temp_list[i]) prior_value = obj.info["ttl"] + 0 + obj.info["leval"] obj = [-prior_value, self.index, obj] self.task_queue.put(obj) self.index += 1 print("current task number:", self.task_queue.qsize()) if (self.task_queue.qsize() == self.state.info["To"] + 5): self.state.info["state"] = 2 #self.lock.release() ip_id = self.IP_FIND() for ip, id in ip_id.items(): packet = stat_packet(id=self.state.info["id"], To=self.state.info["To"], Tu=self.state.info["Tu"], state=2) self.send(packet, ip) elif (self.task_queue.qsize() == self.state.info["Tu"] + 5): self.state.info['state'] = 1 #self.lock.release() ip_id = self.IP_FIND() for ip, id in ip_id.items(): packet = stat_packet(id=self.state.info["id"], To=self.state.info["To"], Tu=self.state.info["Tu"], state=1) self.send(packet, ip) self.lock.release() self.lock3.release() elif obj.info["cfrag"] != None: self.lock2.acquire() print("receive cfrag...........") if obj.info["version"] in self.old_version: self.lock2.release() return if obj.info["CID"] not in self.tempo_cfrags: # cfrag handle print("accumulating cfrag.............") temp = obj.info["cfrag"] version = obj.info["version"] temp = cfrags.CapsuleFrag.from_bytes(temp) self.tempo_cfrags[obj.info["CID"]] = {version: [temp]} # print(self.tempo_cfrags) else: temp = obj.info["cfrag"] version = obj.info["version"] temp = cfrags.CapsuleFrag.from_bytes(temp) if version in self.tempo_cfrags[obj.info["CID"]]: self.tempo_cfrags[obj.info["CID"]][version].append(temp) else: self.tempo_cfrags[obj.info["CID"]][version] = [temp] if len(self.tempo_cfrags[obj.info["CID"]] [version]) >= THRESHOLD: #print(self.tempo_cfrags[obj.info["CID"]]) capsule = self.record[obj.info["CID"]].pop() #print(capsule) for cfrag in self.tempo_cfrags[obj.info["CID"]][version]: capsule.attach_cfrag(cfrag) print("begin decrypting") self.file_download_and_decrypt(obj.info["CID"], capsule) self.tempo_cfrags[obj.info["CID"]].pop(version) self.old_version.add(version) self.lock2.release()
def decrypt(): # Get data from request json_data = json.loads(request.data.decode('utf-8')) ciphertext, policy_id, capsule_id, alice_pubkey, bob_pubkey, bob_privkey, alice_signing_pubkey = json_data['ciphertext'], json_data[ 'policy_id'], json_data['capsule_id'], json_data['alice_pubkey'], json_data['bob_pubkey'], json_data['bob_privkey'], json_data['alice_signing_pubkey'] # convert to bytes ciphertext = string_to_bytes(ciphertext) try: capsule_byte = r.get(capsule_id).decode("utf-8") capsule = pre.Capsule.from_bytes(string_to_bytes(capsule_byte), params.UmbralParameters(SECP256K1)) alice_pubkey = string_to_bytes(alice_pubkey) alice_pubkey = keys.UmbralPublicKey.from_bytes(alice_pubkey) bob_pubkey = string_to_bytes(bob_pubkey) bob_pubkey = keys.UmbralPublicKey.from_bytes(bob_pubkey) bob_privkey = string_to_bytes(bob_privkey) bob_privkey = keys.UmbralPrivateKey.from_bytes(bob_privkey) alice_signing_pubkey = string_to_bytes(alice_signing_pubkey) alice_signing_pubkey = keys.UmbralPublicKey.from_bytes( alice_signing_pubkey) try: capsule.set_correctness_keys( alice_pubkey, bob_pubkey, alice_signing_pubkey) except: print("Unexpected error:", sys.exc_info()[0]) traceback.print_exception(*sys.exc_info()[0]) # Perform re-encryption request bob_cfrags = mock_kms.reencrypt(policy_id, capsule, 10) # Simulate capsule handoff, and set the correctness keys. # Correctness keys are used to prove that a cfrag is correct and not modified # by a proxy node in the network. They must be set to use the `decrypt` and # `attach_cfrag` funtions. bob_capsule = capsule try: bob_capsule.set_correctness_keys( alice_pubkey, bob_pubkey, alice_signing_pubkey) except: print("Unexpected error:", sys.exc_info()[0]) traceback.print_exception(*sys.exc_info()[0]) for cfrag in bob_cfrags: bob_capsule.attach_cfrag(cfrag) decrypted_data = pre.decrypt( ciphertext, bob_capsule, bob_privkey, alice_signing_pubkey) return jsonify({ "decrypted_data": decrypted_data.decode('utf-8'), }) except Exception as e: print("except", str(e), sys.exc_info()[0]) traceback.print_exception(*sys.exc_info()[0]) return jsonify({ "decrypted_data": None, })
alices_public_key = alices_private_key.get_pubkey() alices_signing_key = keys.UmbralPrivateKey.gen_key() alices_verifying_key = alices_signing_key.get_pubkey() alices_signer = signing.Signer(private_key=alices_signing_key) # 为Bob生成密钥对 bobs_private_key = keys.UmbralPrivateKey.gen_key() bobs_public_key = bobs_private_key.get_pubkey() # 用alices的私钥加密明文 plaintext = b'Hello! my name is Yapie!' #明文,,换成你的病例就行了 ciphertext, capsule_temp = pre.encrypt(alices_public_key, plaintext) capsule_bytes = capsule_temp.to_bytes() parameters = params.UmbralParameters(SECP256K1) capsule = pre.Capsule.from_bytes(capsule_bytes, parameters) # 尝试用alice的私钥是否能够解密. cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=alices_private_key) # Alice 生成 "M of N" 的解密条件,意思是bob能收到20个代理中的十个以上的重加密就可以解密密文 # In this example, 10 out of 20. kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key, signer=alices_signer, receiving_pubkey=bobs_public_key, threshold=10, N=20) #代理重加密.bob确认收到的cfrags数量,大于10Bob便可以解密密文
def bytes_to_capsule(capsule_bytes): parameters = params.UmbralParameters(SECP256K1) capsule = pre.Capsule.from_bytes(capsule_bytes, parameters) return capsule
def receive(self): #获取本地IP sock_receiver=socket(AF_INET,SOCK_STREAM,0) sock_receiver.bind((self.IP,self.port)) sock_receiver.listen(10) sock_receiver.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #监听端口配置 while True: conn,address=sock_receiver.accept() #获得发送方IP地址和端口 total_data=[] while True: data=conn.recv(1024) if not data:break total_data.append(data) data_receive=b''.join(total_data) obj=pickle.loads(data_receive) #数据接收 if isinstance(obj,info_packet): if obj.info["check"]==2:#接收到公钥 capsule=self.record[obj.info["tx_hash"]] pub_key = keys.UmbralPublicKey.from_bytes(obj.info["pub_key1"]) print("接收到公钥:",pub_key) kfrags_=pre.generate_kfrags(self.pri_key,pub_key,THRESHOLD,SPLIT_NUMBER,self.signer) #序列化 capsule = capsule.to_bytes() pub_key1=pub_key.to_bytes()#目标公钥 pub_key2=self.pub_key.to_bytes()#自身公钥 verify_key=self.verifying_key.to_bytes()#验证公钥 IP=self.IP_FIND()#可连接IP #IP处理 if obj.info["IP"] in IP: IP.remove(obj.info["IP"]) if len(IP)>=THRESHOLD: for i,kfrag in enumerate(kfrags_): kfrag = kfrag.to_bytes() responce = info_packet(capsule=capsule, kfrag=kfrag, tx_hash=obj.info["tx_hash"], IP=obj.info["IP"],pub_key1=pub_key1,pub_key2=pub_key2,verify_key=verify_key,check=3) self.send(packet=responce,des_IP=IP[i%len(IP)]) elif obj.info["check"]==0: #接收到初始请求 # capsule二值化 print("received the request") capsule=self.record[obj.info["tx_hash"]] capsule=capsule.to_bytes() # 自身公钥二值化 print(capsule) pub_key2=self.pub_key.to_bytes() verify_key=self.verifying_key.to_bytes() responce=info_packet(capsule=capsule,tx_hash=obj.info["tx_hash"],check=1,IP=self.IP,pub_key2=pub_key2,verify_key=verify_key) print(obj.info["IP"]) self.send(packet=responce,des_IP=obj.info["IP"]) elif obj.info["check"]==1: #接收到请求确认 #capsule还原 capsule=obj.info["capsule"] param = params.UmbralParameters(self.curve) capsule = pre.Capsule.from_bytes(capsule,param) #公钥还原 pub_key2 = obj.info["pub_key2"] pub_key2 = keys.UmbralPublicKey.from_bytes(pub_key2) verify_key = obj.info["verify_key"] verify_key = keys.UmbralPublicKey.from_bytes(verify_key) capsule.set_correctness_keys(pub_key2,self.pub_key,verify_key) self.record[obj.info["tx_hash"]]=capsule pub_key=self.pub_key.to_bytes() responce=info_packet(tx_hash=obj.info["tx_hash"],IP=self.IP,pub_key1=pub_key,check=2) self.send(packet=responce,des_IP=obj.info["IP"]) elif obj.info["check"]==3:#接收到重加密碎片 #kfrag处理 kfrag=obj.info["kfrag"] kfrag=kfrags.KFrag.from_bytes(kfrag) #capsule处理 capsule=obj.info["capsule"] param = params.UmbralParameters(self.curve) capsule = pre.Capsule.from_bytes(capsule, param) #公钥处理 pub_key1 = obj.info["pub_key1"] pub_key1=keys.UmbralPublicKey.from_bytes(pub_key1) pub_key2 = obj.info["pub_key2"] pub_key2 = keys.UmbralPublicKey.from_bytes(pub_key2) verify_key = obj.info["verify_key"] verify_key = keys.UmbralPublicKey.from_bytes(verify_key) #重加密 capsule.set_correctness_keys(pub_key2,pub_key1,verify_key) print(capsule) cfrag=pre.reencrypt(kfrag,capsule) print("CFrag完成",cfrag) #cfrag处理 cfrag=cfrag.to_bytes() cfrag_packet=info_packet(cfrag=cfrag,tx_hash=obj.info["tx_hash"]) self.send(packet=cfrag_packet, des_IP=obj.info["IP"]) elif obj.info["cfrag"]!=None: print("收到cfrag数据帧") if obj.info["tx_hash"] not in self.tempo_cfrags: #cfrag处理 print("开始累积cfrag") temp=obj.info["cfrag"] temp=cfrags.CapsuleFrag.from_bytes(temp) self.tempo_cfrags[obj.info["tx_hash"]]=[temp] #print(self.tempo_cfrags) if len(self.tempo_cfrags[obj.info["tx_hash"]])>=THRESHOLD: #开始解密 capsule=self.record[obj.info["tx_hash"]] for cfrag in self.tempo_cfrags[obj.info["tx_hash"]]: capsule.attach_frag(cfrag) self.file_download_and_decrypt(obj.info["tx_hash"],capsule) #删除记录 else: temp = obj.info["cfrag"] temp = cfrags.CapsuleFrag.from_bytes(temp) self.tempo_cfrags[obj.info["tx_hash"]].append(temp) if len(self.tempo_cfrags[obj.info["tx_hash"]]) >= THRESHOLD: # 开始解密 print(self.tempo_cfrags[obj.info["tx_hash"]]) capsule = self.record[obj.info["tx_hash"]] print(capsule) for cfrag in self.tempo_cfrags[obj.info["tx_hash"]]: capsule.attach_cfrag(cfrag) print("开始解密") self.file_download_and_decrypt(obj.info["tx_hash"], capsule)