def reencrypt(kfrag: KFrag, capsule: Capsule, provide_proof: bool = True, metadata: Optional[bytes] = None, verify_kfrag: bool = True) -> CapsuleFrag: if not isinstance(capsule, Capsule) or not capsule.verify(): raise Capsule.NotValid if verify_kfrag: if not isinstance(kfrag, KFrag) or not kfrag.verify_for_capsule(capsule): raise KFrag.NotValid rk = kfrag.bn_key e1 = rk * capsule.point_e # type: Any v1 = rk * capsule.point_v # type: Any cfrag = CapsuleFrag(point_e1=e1, point_v1=v1, kfrag_id=kfrag.id, point_precursor=kfrag.point_precursor) if provide_proof: cfrag.prove_correctness(capsule, kfrag, metadata) return cfrag
def test_cfrag_serialization_with_proof_but_no_metadata( prepared_capsule, kfrags): for kfrag in kfrags: cfrag = pre.reencrypt(kfrag, prepared_capsule, provide_proof=True) cfrag_bytes = cfrag.to_bytes() proof = cfrag.proof assert proof is not None assert proof.metadata is None # A CFrag can be represented as the 131 total bytes of three Points (33 each) and a CurveBN (32). # TODO: Figure out final size for CFrags with proofs # assert len(cfrag_bytes) == 33 + 33 + 33 + 32 == 131 new_cfrag = CapsuleFrag.from_bytes(cfrag_bytes) assert new_cfrag.point_e1 == cfrag.point_e1 assert new_cfrag.point_v1 == cfrag.point_v1 assert new_cfrag.kfrag_id == cfrag.kfrag_id assert new_cfrag.point_precursor == cfrag.point_precursor new_proof = new_cfrag.proof assert new_proof is not None assert new_proof.point_e2 == proof.point_e2 assert new_proof.point_v2 == proof.point_v2 assert new_proof.point_kfrag_commitment == proof.point_kfrag_commitment assert new_proof.point_kfrag_pok == proof.point_kfrag_pok assert new_proof.bn_sig == proof.bn_sig assert new_proof.metadata is None
def test_cfrag_serialization_with_proof_and_metadata(prepared_capsule, kfrags): # Example of potential metadata to describe the re-encryption request metadata = b'This is an example of metadata for re-encryption request' for kfrag in kfrags: cfrag = pre.reencrypt(kfrag, prepared_capsule, provide_proof=True, metadata=metadata) cfrag_bytes = cfrag.to_bytes() proof = cfrag.proof assert proof is not None assert proof.metadata is not None new_cfrag = CapsuleFrag.from_bytes(cfrag_bytes) assert new_cfrag.point_e1 == cfrag.point_e1 assert new_cfrag.point_v1 == cfrag.point_v1 assert new_cfrag.kfrag_id == cfrag.kfrag_id assert new_cfrag.point_precursor == cfrag.point_precursor new_proof = new_cfrag.proof assert new_proof is not None assert new_proof.point_e2 == proof.point_e2 assert new_proof.point_v2 == proof.point_v2 assert new_proof.point_kfrag_commitment == proof.point_kfrag_commitment assert new_proof.point_kfrag_pok == proof.point_kfrag_pok assert new_proof.bn_sig == proof.bn_sig assert new_proof.metadata == metadata assert new_proof.metadata == proof.metadata
def test_cannot_attach_cfrag_without_proof(): """ However, even when properly attaching keys, we can't attach the CFrag if it is unproven. """ params = default_params() capsule = Capsule(params, point_e=Point.gen_rand(), point_v=Point.gen_rand(), bn_sig=CurveBN.gen_rand()) cfrag = CapsuleFrag( point_e1=Point.gen_rand(), point_v1=Point.gen_rand(), kfrag_id=os.urandom(10), point_precursor=Point.gen_rand(), ) key_details = capsule.set_correctness_keys( UmbralPrivateKey.gen_key().get_pubkey(), UmbralPrivateKey.gen_key().get_pubkey(), UmbralPrivateKey.gen_key().get_pubkey()) delegating_details, receiving_details, verifying_details = key_details assert all((delegating_details, receiving_details, verifying_details)) with pytest.raises(cfrag.NoProofProvided): capsule.attach_cfrag(cfrag)
def test_cfrag_serialization_no_proof_no_metadata(prepared_capsule, kfrags): for kfrag in kfrags: cfrag = pre.reencrypt(kfrag, prepared_capsule, provide_proof=False) cfrag_bytes = cfrag.to_bytes() proof = cfrag.proof assert proof is None assert len(cfrag_bytes) == CapsuleFrag.expected_bytes_length() new_cfrag = CapsuleFrag.from_bytes(cfrag_bytes) assert new_cfrag.point_e1 == cfrag.point_e1 assert new_cfrag.point_v1 == cfrag.point_v1 assert new_cfrag.kfrag_id == cfrag.kfrag_id assert new_cfrag.point_precursor == cfrag.point_precursor new_proof = new_cfrag.proof assert new_proof is None
def hop_reencrypt(kfrag: KFrag, cfrag: CapsuleFrag, capsule: Capsule, metadata: Optional[bytes] = None, provide_proof: bool = True) -> CapsuleFrag: rk = kfrag.bn_key e1 = rk * cfrag.point_e1 v1 = rk * cfrag.point_v1 cfrag = CapsuleFrag(point_e1=e1, point_v1=v1, kfrag_id=kfrag.id, point_precursor=kfrag.point_precursor) if provide_proof: cfrag.prove_correctness(capsule, kfrag, metadata) return cfrag
def decrypt(): api = ipfsapi.connect('127.0.0.1', 5001) res = {} cfrags = list() if request.headers['Content-Type'] == 'application/json': account = request.json['account'] ciphertexthex = request.json['ciphertext'] b_ciphertext = bytes.fromhex(ciphertexthex) decryptkey = request.json['decryptkey'] b_decryptkey = bytes.fromhex(decryptkey) deckey = UmbralPrivateKey.from_bytes(b_decryptkey) capsuleaddr = request.json['capsule'] b_capsule_all = api.cat(capsuleaddr) splitarr1 = b_capsule_all.split(b'ZAtech') b_basic_capsule = splitarr1[0] capsule = Capsule.from_bytes(b_basic_capsule, UmbralParameters(Curve(714))) print("0") correctness_keys = splitarr1[1] splitarr2 = correctness_keys.split(b'ZBtech') delegating = UmbralPublicKey.from_bytes(splitarr2[0]) receiving = UmbralPublicKey.from_bytes(splitarr2[1]) verifying = UmbralPublicKey.from_bytes(splitarr2[2]) # 用带入的参数capsule_all的各种byte,重现绑定correctness keys的capsule. capsule.set_correctness_keys(delegating=delegating, receiving=receiving, verifying=verifying) print("1") b_cfrag_all = splitarr1[2].split(b'ZCtech') for b_cfrag in b_cfrag_all: cfrags.append(CapsuleFrag.from_bytes(b_cfrag)) for cfrag in cfrags: capsule.attach_cfrag(cfrag) print("2") print(capsule) print(capsule.get_correctness_keys()) print(cfrags) cleartext = pre.decrypt(ciphertext=b_ciphertext, capsule=capsule, decrypting_key=deckey) print("3") res = {"cleartext": cleartext.decode("utf-8")} print("\nbob_cleartext: ") print(cleartext) return jsonify(res), {'Content-Type': 'application/json'} return
def test_cfrags(): vector_file = os.path.join('vectors', 'vectors_cfrags.json') try: with open(vector_file) as f: vector_suite = json.load(f) except OSError: raise params = default_params() capsule = pre.Capsule.from_bytes(bytes.fromhex(vector_suite['capsule']), params=params) verifying_key = UmbralPublicKey.from_bytes( bytes.fromhex(vector_suite['verifying_key'])) delegating_key = UmbralPublicKey.from_bytes( bytes.fromhex(vector_suite['delegating_key'])) receiving_key = UmbralPublicKey.from_bytes( bytes.fromhex(vector_suite['receiving_key'])) kfrags_n_cfrags = [ (KFrag.from_bytes(bytes.fromhex(json_kfrag['kfrag'])), CapsuleFrag.from_bytes(bytes.fromhex(json_kfrag['cfrag']))) for json_kfrag in vector_suite['vectors'] ] capsule.set_correctness_keys(delegating=delegating_key, receiving=receiving_key, verifying=verifying_key) for kfrag, cfrag in kfrags_n_cfrags: assert kfrag.verify(signing_pubkey=verifying_key, delegating_pubkey=delegating_key, receiving_pubkey=receiving_key), \ 'Invalid KFrag {}'.format(kfrag.to_bytes().hex()) new_cfrag = pre.reencrypt(kfrag, capsule, provide_proof=False) assert new_cfrag.point_e1 == cfrag.point_e1 assert new_cfrag.point_v1 == cfrag.point_v1 assert new_cfrag.kfrag_id == cfrag.kfrag_id assert new_cfrag.point_precursor == cfrag.point_precursor assert new_cfrag.proof is None assert cfrag.to_bytes() == new_cfrag.to_bytes()
def test_cannot_attach_cfrag_without_keys(): """ We need the proper keys to verify the correctness of CFrags in order to attach them to a Capsule. """ params = default_params() capsule = Capsule(params, point_e=Point.gen_rand(), point_v=Point.gen_rand(), bn_sig=CurveBN.gen_rand()) cfrag = CapsuleFrag( point_e1=Point.gen_rand(), point_v1=Point.gen_rand(), kfrag_id=os.urandom(10), point_precursor=Point.gen_rand(), ) with pytest.raises(TypeError): capsule.attach_cfrag(cfrag)
def test_bob_can_issue_a_work_order_to_a_specific_ursula( enacted_federated_policy, federated_bob, federated_alice, federated_ursulas, capsule_side_channel): """ Now that Bob has his list of Ursulas, he can issue a WorkOrder to one. Upon receiving the WorkOrder, Ursula saves it and responds by re-encrypting and giving Bob a cFrag. This is a multipart test; it shows proper relations between the Characters Ursula and Bob and also proper interchange between a KFrag, Capsule, and CFrag object in the context of REST-driven proxy re-encryption. """ # We pick up our story with Bob already having followed the treasure map above, ie: hrac, treasure_map = enacted_federated_policy.hrac, enacted_federated_policy.treasure_map federated_bob.start_learning_loop() federated_bob.follow_treasure_map(treasure_map=treasure_map, block=True, timeout=1) assert len(federated_bob.known_nodes) == len(federated_ursulas) # Bob has no saved work orders yet, ever. assert len(federated_bob._completed_work_orders) == 0 # We'll test against just a single Ursula - here, we make a WorkOrder for just one. # We can pass any number of capsules as args; here we pass just one. capsule = capsule_side_channel().capsule capsule.set_correctness_keys( delegating=enacted_federated_policy.public_key, receiving=federated_bob.public_keys(DecryptingPower), verifying=federated_alice.stamp.as_umbral_pubkey()) work_orders, _ = federated_bob.work_orders_for_capsules( capsule, treasure_map=treasure_map, alice_verifying_key=federated_alice.stamp.as_umbral_pubkey(), num_ursulas=1) # Again: one Ursula, one work_order. assert len(work_orders) == 1 # Since we didn't tell Bob to cache the WorkOrders, Bob didn't save it. assert len(federated_bob._completed_work_orders) == 0 # This time, we'll tell Bob to cache it. retained_work_orders, _ = federated_bob.work_orders_for_capsules( capsule, treasure_map=treasure_map, alice_verifying_key=federated_alice.stamp.as_umbral_pubkey(), num_ursulas=1) # The work order we just made is not yet complete, of course. address, work_order = list(retained_work_orders.items())[0] assert work_order.completed is False # **** RE-ENCRYPTION HAPPENS HERE! **** _success, cfrags = federated_bob._reencrypt(work_order, retain_cfrags=True) # We only gave one Capsule, so we only got one cFrag. assert len(cfrags) == 1 the_cfrag = cfrags[0] # ...and the work order is complete. assert work_order.completed # Attach the CFrag to the Capsule. capsule.attach_cfrag(the_cfrag) # Having received the cFrag, Bob also saved the WorkOrder as complete. assert len(federated_bob._completed_work_orders.by_ursula[address]) == 1 # OK, so cool - Bob has his cFrag! Let's make sure everything went properly. First, we'll show that it is in fact # the correct cFrag (ie, that Ursula performed re-encryption properly). for u in federated_ursulas: if u.rest_interface.port == work_order.ursula.rest_interface.port: ursula = u break else: raise RuntimeError( "We've lost track of the Ursula that has the WorkOrder. Can't really proceed." ) with ursula.datastore.describe( PolicyArrangement, work_order.arrangement_id.hex()) as policy_arrangement: the_kfrag = policy_arrangement.kfrag the_correct_cfrag = pre.reencrypt(the_kfrag, capsule) # The first CFRAG_LENGTH_WITHOUT_PROOF bytes (ie, the cfrag proper, not the proof material), are the same: assert bytes(the_cfrag)[:CapsuleFrag.expected_bytes_length()] == bytes( the_correct_cfrag)[:CapsuleFrag.expected_bytes_length( )] # It's the correct cfrag! assert the_correct_cfrag.verify_correctness(capsule) # Now we'll show that Ursula saved the correct WorkOrder. with ursula.datastore.query_by( Workorder, filter_field='bob_verifying_key', filter_func=lambda bob_key: bob_key == federated_bob.stamp. as_umbral_pubkey()) as work_orders_from_bob: assert len(work_orders_from_bob) == 1 assert work_orders_from_bob[ 0].bob_signature == work_order.receipt_signature
def test_bob_can_issue_a_work_order_to_a_specific_ursula(enacted_federated_policy, federated_bob, federated_alice, federated_ursulas, capsule_side_channel): """ Now that Bob has his list of Ursulas, he can issue a WorkOrder to one. Upon receiving the WorkOrder, Ursula saves it and responds by re-encrypting and giving Bob a cFrag. This is a multipart test; it shows proper relations between the Characters Ursula and Bob and also proper interchange between a KFrag, Capsule, and CFrag object in the context of REST-driven proxy re-encryption. """ # We pick up our story with Bob already having followed the treasure map above, ie: hrac, treasure_map = enacted_federated_policy.hrac(), enacted_federated_policy.treasure_map map_id = treasure_map.public_id() federated_bob.treasure_maps[map_id] = treasure_map federated_bob.start_learning_loop() federated_bob.follow_treasure_map(map_id=map_id, block=True, timeout=1) assert len(federated_bob.known_nodes) == len(federated_ursulas) # Bob has no saved work orders yet, ever. assert len(federated_bob._saved_work_orders) == 0 # We'll test against just a single Ursula - here, we make a WorkOrder for just one. # We can pass any number of capsules as args; here we pass just one. capsule = capsule_side_channel[0].capsule capsule.set_correctness_keys(delegating=enacted_federated_policy.public_key, receiving=federated_bob.public_keys(DecryptingPower), verifying=federated_alice.stamp.as_umbral_pubkey()) work_orders = federated_bob.generate_work_orders(map_id, capsule, num_ursulas=1) # Again: one Ursula, one work_order. assert len(work_orders) == 1 # Bob saved the WorkOrder. assert len(federated_bob._saved_work_orders) == 1 # And the Ursula. assert len(federated_bob._saved_work_orders.ursulas) == 1 ursula_id, work_order = list(work_orders.items())[0] # The work order is not yet complete, of course. assert work_order.completed is False # **** RE-ENCRYPTION HAPPENS HERE! **** cfrags = federated_bob.get_reencrypted_cfrags(work_order) # We only gave one Capsule, so we only got one cFrag. assert len(cfrags) == 1 the_cfrag = cfrags[0] # ...and the work order is complete. assert work_order.completed # Attach the CFrag to the Capsule. capsule.attach_cfrag(the_cfrag) # Having received the cFrag, Bob also saved the WorkOrder as complete. assert len(federated_bob._saved_work_orders.by_ursula[ursula_id]) == 1 # OK, so cool - Bob has his cFrag! Let's make sure everything went properly. First, we'll show that it is in fact # the correct cFrag (ie, that Ursula performed re-encryption properly). for u in federated_ursulas: if u.rest_information()[0].port == work_order.ursula.rest_information()[0].port: ursula = u break else: raise RuntimeError("We've lost track of the Ursula that has the WorkOrder. Can't really proceed.") kfrag_bytes = ursula.datastore.get_policy_arrangement( work_order.arrangement_id.hex().encode()).kfrag the_kfrag = KFrag.from_bytes(kfrag_bytes) the_correct_cfrag = pre.reencrypt(the_kfrag, capsule) # The first CFRAG_LENGTH_WITHOUT_PROOF bytes (ie, the cfrag proper, not the proof material), are the same: assert bytes(the_cfrag)[:CapsuleFrag.expected_bytes_length()] == bytes( the_correct_cfrag)[:CapsuleFrag.expected_bytes_length()] # It's the correct cfrag! assert the_correct_cfrag.verify_correctness(capsule) # Now we'll show that Ursula saved the correct WorkOrder. work_orders_from_bob = ursula.work_orders(bob=federated_bob) assert len(work_orders_from_bob) == 1 assert work_orders_from_bob[0] == work_order
def fetch(): api = ipfsapi.connect('127.0.0.1', 5001) if request.headers['Content-Type'] == 'application/json': account = request.json['account'] # 所有的传入参数都是hex key capsuleaddr = request.json['capsule'] b_capsule_all = api.cat(capsuleaddr) splitarr1 = b_capsule_all.split(b'ZAtech') b_basic_capsule = splitarr1[0] capsule = Capsule.from_bytes(b_basic_capsule, UmbralParameters(Curve(714))) correctness_keys = splitarr1[1] splitarr2 = correctness_keys.split(b'ZBtech') delegating = UmbralPublicKey.from_bytes(splitarr2[0]) receiving = UmbralPublicKey.from_bytes(splitarr2[1]) verifying = UmbralPublicKey.from_bytes(splitarr2[2]) # print(splitarr1[0]) # print(splitarr1[1]) # print(splitarr2[0]) # print(splitarr2[1]) # print(splitarr2[2]) print(delegating) print(receiving) print(verifying) caddrs = request.json['addresses'] # 用带入的参数capsule_all的各种byte,重现绑定correctness keys的capsule. capsule.set_correctness_keys(delegating=delegating, receiving=receiving, verifying=verifying) print(capsule.get_correctness_keys()) cfrags = list() all_bytes = b'' index = 0 for addr in caddrs: index += 1 b_cfrag = api.cat(addr) all_bytes += b_cfrag if index < len(caddrs): all_bytes += b'ZCtech' cfrags.append(CapsuleFrag.from_bytes(api.cat(addr))) for cfrag in cfrags: capsule.attach_cfrag(cfrag) # 再将append的内容写入capsule,然后就可以将解密单独拎出来。 b_capsule_all += b'ZAtech' + all_bytes savedcapaddr = api.add_bytes(b_capsule_all) # splitarr = b_capsule_all.split(b'ZAtech') # splitarrmiddle = splitarr[1].split(b'ZBtech') # splitarrlast = splitarr[2].split(b'ZCtech') # print(len(cfrags)) # for s in splitarrmiddle: # print(s) # print(len(splitarrlast)) # for s in splitarrlast: # print(s) res = {"capsule": savedcapaddr} return jsonify(res), {'Content-Type': 'application/json'} return
def test_lifecycle_with_serialization(N, M, signing_mode, curve=default_curve()): """ This test is a variant of test_simple_api, but with intermediate serialization/deserialization steps, modeling how pyUmbral artifacts (such as keys, ciphertexts, etc) will actually be used. These intermediate steps are in between the different 'usage domains' in NuCypher, namely, key generation, delegation, encryption, decryption by Alice, re-encryption by Ursula, and decryption by Bob. Manually injects UmbralParameters for multi-curve testing. """ # Convenience method to avoid replicating key generation code def new_keypair_bytes(): privkey = UmbralPrivateKey.gen_key(params=params) return privkey.to_bytes(), privkey.get_pubkey().to_bytes() ## SETUP params = UmbralParameters(curve=curve) delegating_privkey_bytes, delegating_pubkey_bytes = new_keypair_bytes() signing_privkey_bytes, signing_pubkey_bytes = new_keypair_bytes() receiving_privkey_bytes, receiving_pubkey_bytes = new_keypair_bytes() ## DELEGATION DOMAIN: ## Alice delegates decryption rights to some Bob by generating a set of ## KFrags, using her delegating private key and Bob's receiving public key delegating_privkey = UmbralPrivateKey.from_bytes(delegating_privkey_bytes, params=params) signing_privkey = UmbralPrivateKey.from_bytes(signing_privkey_bytes, params=params) receiving_pubkey = UmbralPublicKey.from_bytes(receiving_pubkey_bytes, params=params) signer = Signer(signing_privkey) sign_delegating_key, sign_receiving_key = signing_mode kfrags = pre.generate_kfrags(delegating_privkey=delegating_privkey, receiving_pubkey=receiving_pubkey, threshold=M, N=N, signer=signer, sign_delegating_key=sign_delegating_key, sign_receiving_key=sign_receiving_key) kfrags_bytes = tuple(map(bytes, kfrags)) del kfrags del signer del delegating_privkey del signing_privkey del receiving_pubkey del params ## ENCRYPTION DOMAIN ## params = UmbralParameters(curve=curve) delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes, params) plain_data = b'peace at dawn' ciphertext, capsule = pre.encrypt(delegating_pubkey, plain_data) capsule_bytes = bytes(capsule) del capsule del delegating_pubkey del params ## DECRYPTION BY ALICE ## params = UmbralParameters(curve=curve) delegating_privkey = UmbralPrivateKey.from_bytes(delegating_privkey_bytes, params=params) capsule = pre.Capsule.from_bytes(capsule_bytes, params) cleartext = pre.decrypt(ciphertext, capsule, delegating_privkey) assert cleartext == plain_data del delegating_privkey del capsule del params ## RE-ENCRYPTION DOMAIN (i.e., Ursula's side) cfrags_bytes = list() for kfrag_bytes in kfrags_bytes: params = UmbralParameters(curve=curve) delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes, params) signing_pubkey = UmbralPublicKey.from_bytes(signing_pubkey_bytes, params) receiving_pubkey = UmbralPublicKey.from_bytes(receiving_pubkey_bytes, params) capsule = pre.Capsule.from_bytes(capsule_bytes, params) capsule.set_correctness_keys(delegating=delegating_pubkey, receiving=receiving_pubkey, verifying=signing_pubkey) # TODO: use params instead of curve? kfrag = KFrag.from_bytes(kfrag_bytes, params.curve) assert kfrag.verify(signing_pubkey, delegating_pubkey, receiving_pubkey, params) cfrag_bytes = bytes(pre.reencrypt(kfrag, capsule)) cfrags_bytes.append(cfrag_bytes) del capsule del kfrag del params del delegating_pubkey del signing_pubkey del receiving_pubkey ## DECRYPTION DOMAIN (i.e., Bob's side) params = UmbralParameters(curve=curve) capsule = pre.Capsule.from_bytes(capsule_bytes, params) delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes, params) signing_pubkey = UmbralPublicKey.from_bytes(signing_pubkey_bytes, params) receiving_privkey = UmbralPrivateKey.from_bytes(receiving_privkey_bytes, params=params) receiving_pubkey = receiving_privkey.get_pubkey() capsule.set_correctness_keys(delegating=delegating_pubkey, receiving=receiving_pubkey, verifying=signing_pubkey) for cfrag_bytes in cfrags_bytes: # TODO: use params instead of curve? cfrag = CapsuleFrag.from_bytes(cfrag_bytes, params.curve) capsule.attach_cfrag(cfrag) reenc_cleartext = pre.decrypt(ciphertext, capsule, receiving_privkey) assert reenc_cleartext == plain_data
def attach_cfrag(self, cfrag: CapsuleFrag) -> None: if cfrag.verify_correctness(self): self._attached_cfrags.append(cfrag) else: error_msg = "CFrag is not correct and cannot be attached to the Capsule" raise UmbralCorrectnessError(error_msg, [cfrag])