def test_bob_can_follow_treasure_map_even_if_he_only_knows_of_one_node( enacted_federated_policy, federated_ursulas, certificates_tempdir): """ Similar to above, but this time, we'll show that if Bob can connect to a single node, he can learn enough to follow the TreasureMap. Also, we'll get the TreasureMap from the hrac alone (ie, not via a side channel). """ from nucypher.characters.lawful import Bob bob = Bob(network_middleware=MockRestMiddleware(), known_certificates_dir=certificates_tempdir, start_learning_now=False, abort_on_learning_error=True, federated_only=True) # Again, let's assume that he received the TreasureMap via a side channel. hrac, treasure_map = enacted_federated_policy.hrac( ), enacted_federated_policy.treasure_map map_id = treasure_map.public_id() bob.treasure_maps[map_id] = treasure_map # Now, let's create a scenario in which Bob knows of only one node. assert len(bob.known_nodes) == 0 first_ursula = list(federated_ursulas).pop(0) bob.remember_node(first_ursula) assert len(bob.known_nodes) == 1 # This time, when he follows the TreasureMap... unknown_nodes, known_nodes = bob.peek_at_treasure_map(map_id=map_id) # Bob already knew about one node; the rest are unknown. assert len(unknown_nodes) == len(treasure_map) - 1 # He needs to actually follow the treasure map to get the rest. bob.follow_treasure_map(map_id=map_id) # The nodes in the learning loop are now his top target, but he's not learning yet. assert not bob._learning_task.running # ...so he hasn't learned anything (ie, Bob still knows of just one node). assert len(bob.known_nodes) == 1 # Now, we'll start his learning loop. bob.start_learning_loop() # ...and block until the unknown_nodes have all been found. d = threads.deferToThread(bob.block_until_specific_nodes_are_known, unknown_nodes) yield d # ...and he now has no more unknown_nodes. assert len(bob.known_nodes) == len(treasure_map)
def get(self): "User should send Bob password to decrypt files" try: user = request.args.get("user") pw = request.args.get("password") label = request.args.get("label") frmt = request.args.get("frmt") except: response = {'message': "Insufficient Query Params"} return make_response(jsonify(response)), 404 keyringBob = NucypherKeyring(account=user) keyringBob.unlock(password=pw) bob = Bob(keyring=keyringBob, known_nodes=[ursula], federated_only=True, learn_on_same_thread=True, domain=TEMPORARY_DOMAIN) bob.join_policy(label.encode(), alice_sig_pubkey) from nucypher.characters.lawful import Enrico global globalStorage enrico1 = Enrico.from_public_keys( verifying_key=globalStorage[label]["data_source_public_key"], policy_encrypting_key=globalStorage[label]["policy_pubkey"]) imgUrl = base_uri + label + "." + frmt response = requests.get(imgUrl) ciphertext = UmbralMessageKit.from_bytes(response.content) decrypted_plaintext = bob.retrieve( ciphertext, label=label.encode(), enrico=enrico1, alice_verifying_key=alice_sig_pubkey) return send_file(io.BytesIO(decrypted_plaintext[0]), mimetype="image/" + frmt, as_attachment=False, attachment_filename='{}.'.format(label) + frmt), 200
def create_policy(self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, first_period_reward: int = None) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.create_policy( bob=bob, label=label, m=m, n=n, expiration=expiration, value=value, first_period_reward=first_period_reward) response_data = { 'label': new_policy.label, 'policy_encrypting_key': new_policy.public_key } return response_data
def grant( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, federated_only: bool = True # TODO: Default for now ) -> dict: from nucypher.characters.lawful import Bob # Operate bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key, federated_only=federated_only) new_policy = self.character.grant(bob, label, m=m, n=n, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp } return response_data
def authorize(self, recipient_pubkeys, max_days=5): powers_and_material = { DecryptingPower: UmbralPublicKey.from_bytes(bytes.fromhex( recipient_pubkeys["enc"])), SigningPower: UmbralPublicKey.from_bytes(bytes.fromhex(recipient_pubkeys["sig"])) } recipient = Bob.from_public_keys( powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=max_days) m, n = self.m, self.n self.ALICE.start_learning_loop(now=True) policy = self.ALICE.grant(recipient, self.label, m=m, n=n, expiration=policy_end_datetime) alices_pubkey = bytes(self.ALICE.stamp) policy_info = { "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": alices_pubkey, "label": self.label.decode("utf-8") } return policy_info
def assignPolicyToSubscriber(subsriber, sub_uuid, event_uuid, publicEnc, publicSign): label = event_uuid.encode() m, n = 1, 1 subenc = UmbralPublicKey.from_bytes(bytes.fromhex(publicEnc)) subsig = UmbralPublicKey.from_bytes(bytes.fromhex(publicSign)) ourCurrentSubscriber = Bob.from_public_keys(verifying_key=subsig, encrypting_key=subenc, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=5) print("Creating access policy for the Doctor...") policy = alicia.grant(bob=ourCurrentSubscriber, label=label, m=m, n=n, expiration=policy_end_datetime) print("Done!") print(ourCurrentSubscriber) policy_info = { "policy_pub_key": policy.public_key.to_bytes().hex(), "policy_sig_key": bytes(alicia.stamp).hex(), "label": label.decode("utf-8"), } return policy_info
def grant(self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.grant(bob=bob, label=label, m=m, n=n, value=value, rate=rate, expiration=expiration, discover_on_this_thread=True) new_policy.publishing_mutex.block_until_success_is_reasonably_likely() response_data = {'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp} return response_data
def grant_access_policy(label, bob_pubkeys): ''' Alicia creates a policy granting access to Bob. The policy is sent to the NuCypher network. ''' alicia = get_alice() label = label.encode() # We create a view of the Bob who's going to be granted access. active_listener = Bob.from_public_keys(verifying_key=bob_pubkeys['sig'], encrypting_key=bob_pubkeys['enc'], federated_only=True) print("Creating access policy for the Listener...") # Policy expiration date policy_end_datetime = maya.now() + datetime.timedelta(days=5) # m-out-of-n: This means Alicia splits the re-encryption key in 2 pieces and # she requires Bob to seek collaboration of at least 1 Ursulas m, n = 1, 2 policy = alicia.grant(bob=active_listener, label=label, m=m, n=n, expiration=policy_end_datetime) print(json.dumps({ "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": bytes(alicia.stamp).hex(), "label": label.decode(), }))
def act_as_bob(self, name): print("act_as_bob") dirname = "accounts/" + name + "/" fname = dirname+"recipent.private.json" with open(fname) as data_file: data = json.load(data_file) enc_privkey = UmbralPrivateKey.from_bytes(bytes.fromhex(data["enc"])) sig_privkey = UmbralPrivateKey.from_bytes(bytes.fromhex(data["sig"])) bob_enc_keypair = DecryptingKeypair(private_key=enc_privkey) bob_sig_keypair = SigningKeypair(private_key=sig_privkey) enc_power = DecryptingPower(keypair=bob_enc_keypair) sig_power = SigningPower(keypair=bob_sig_keypair) power_ups = [enc_power, sig_power] bob = Bob( is_me=True, federated_only=True, crypto_power_ups=power_ups, start_learning_now=True, abort_on_learning_error=True, known_nodes=[self.ursula], save_metadata=False, network_middleware=RestMiddleware(), ) return bob
def _mock_ursula_reencrypts(ursula): delegating_privkey = SecretKey.random() capsule, _ciphertext = encrypt(delegating_privkey.public_key(), b'unused') signing_privkey = SecretKey.random() signing_pubkey = signing_privkey.public_key() signer = Signer(signing_privkey) priv_key_bob = SecretKey.random() pub_key_bob = priv_key_bob.public_key() kfrags = generate_kfrags(delegating_sk=delegating_privkey, signer=signer, receiving_pk=pub_key_bob, threshold=2, num_kfrags=4, sign_delegating_key=False, sign_receiving_key=False) ursula_pubkey = ursula.stamp.as_umbral_pubkey() alice_address = canonical_address_from_umbral_key(signing_pubkey) blockhash = bytes(32) specification = b''.join((bytes(capsule), bytes(ursula_pubkey), bytes(ursula.decentralized_identity_evidence), alice_address, blockhash)) bobs_signer = Signer(priv_key_bob) task_signature = bytes(bobs_signer.sign(specification)) cfrag = reencrypt(capsule, kfrags[0]) cfrag_signature = ursula.stamp(bytes(cfrag)) bob = Bob.from_public_keys(verifying_key=pub_key_bob) return WorkOrder.PRETask(capsule, task_signature, cfrag, cfrag_signature)
def create_policy( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, federated_only: bool = True, # TODO: Default for now ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key, federated_only=federated_only) new_policy = self.character.create_policy(bob, label, m, n, federated=federated_only) response_data = { 'label': new_policy.label, 'policy_encrypting_key': new_policy.public_key } return response_data
def initialize_bob(bob_privkeys): ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI, federated_only=True, minimum_stake=0) TEMP_DOCTOR_DIR = "{}/listener-files".format( os.path.dirname(os.path.abspath(__file__))) # Remove previous demo files and create new ones shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True) bob_enc_keypair = DecryptingKeypair(private_key=bob_privkeys["enc"]) bob_sig_keypair = SigningKeypair(private_key=bob_privkeys["sig"]) enc_power = DecryptingPower(keypair=bob_enc_keypair) sig_power = SigningPower(keypair=bob_sig_keypair) power_ups = [enc_power, sig_power] print("Creating the Listener ...") listener = Bob( domains={TEMPORARY_DOMAIN}, federated_only=True, crypto_power_ups=power_ups, start_learning_now=True, abort_on_learning_error=True, known_nodes=[ursula], save_metadata=False, network_middleware=RestMiddleware(), ) print("Listener = ", listener) return listener
def from_rest_payload(cls, arrangement_id, rest_payload, ursula_pubkey_bytes, alice_address): payload_splitter = BytestringSplitter(Signature) + key_splitter payload_elements = payload_splitter(rest_payload, msgpack_remainder=True) signature, bob_pubkey_sig, (tasks_bytes, blockhash) = payload_elements # TODO: check freshness of blockhash? # Check receipt receipt_bytes = b"wo:" + ursula_pubkey_bytes + msgpack.dumps(tasks_bytes) if not signature.verify(receipt_bytes, bob_pubkey_sig): raise InvalidSignature() tasks = [] for task_bytes in tasks_bytes: task = cls.Task.from_bytes(task_bytes) tasks.append(task) # Each task signature has to match the original specification specification = task.get_specification(ursula_pubkey_bytes, alice_address, blockhash) if not task.signature.verify(specification, bob_pubkey_sig): raise InvalidSignature() bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob=bob, arrangement_id=arrangement_id, tasks=tasks, alice_address=alice_address, blockhash=blockhash, receipt_signature=signature)
def grant( self, bob_encrypting_key: PublicKey, bob_verifying_key: PublicKey, label: bytes, threshold: int, shares: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.implementer.grant(bob=bob, label=label, threshold=threshold, shares=shares, value=value, rate=rate, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, # For the users of this interface, Publisher is always the same as Alice, # so we are only returning the Alice's key. 'alice_verifying_key': self.implementer.stamp.as_umbral_pubkey() } return response_data
def create_policy(): """ Character control endpoint for creating a policy and making arrangements with Ursulas. This is an unfinished API endpoint. You are probably looking for grant. """ # TODO: Needs input cleansing and validation # TODO: Provide more informative errors try: request_data = json.loads(request.data) bob_pubkey = bytes.fromhex(request_data['bob_encrypting_key']) label = b64decode(request_data['label']) # TODO: Do we change this to something like "threshold" m, n = request_data['m'], request_data['n'] federated_only = True # const for now bob = Bob.from_public_keys( { DecryptingPower: bob_pubkey, SigningPower: None }, federated_only=True) except (KeyError, JSONDecodeError) as e: return Response(str(e), status=400) new_policy = drone_alice.create_policy(bob, label, m, n, federated=federated_only) # TODO: Serialize the policy return Response('Policy created!', status=200)
def from_rest_payload(cls, arrangement_id, rest_payload): # TODO: Use JSON instead? This is a mess. payload_splitter = BytestringSplitter(Signature) + key_splitter signature, bob_pubkey_sig, remainder = payload_splitter( rest_payload, msgpack_remainder=True) receipt_bytes, *remainder = remainder packed_capsules, packed_signatures, *remainder = remainder alice_address, alice_address_signature = remainder alice_address_signature = Signature.from_bytes(alice_address_signature) if not alice_address_signature.verify(alice_address, bob_pubkey_sig): raise cls.NotFromBob() capsules, capsule_signatures = list(), list() for capsule_bytes, capsule_signature in zip( msgpack.loads(packed_capsules), msgpack.loads(packed_signatures)): capsules.append( Capsule.from_bytes(capsule_bytes, params=default_params())) capsule_signature = Signature.from_bytes(capsule_signature) capsule_signatures.append(capsule_signature) if not capsule_signature.verify(capsule_bytes, bob_pubkey_sig): raise cls.NotFromBob() verified = signature.verify(receipt_bytes, bob_pubkey_sig) if not verified: raise cls.NotFromBob() bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob, arrangement_id, capsules, capsule_signatures, alice_address, alice_address_signature, receipt_bytes, signature)
def grant( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.grant(bob=bob, label=label, m=m, n=n, value=value, rate=rate, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp } return response_data
def generate_charlie(): shutil.rmtree(TEMP_CHARLIE_DIR, ignore_errors=True) ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL, federated_only=True, minimum_stake=0) # To create a Bob, we need the charlie's private keys previously generated. from charlie_keys import get_charlie_privkeys charlie_keys = get_charlie_privkeys() bob_enc_keypair = DecryptingKeypair(private_key=charlie_keys["enc"]) bob_sig_keypair = SigningKeypair(private_key=charlie_keys["sig"]) enc_power = DecryptingPower(keypair=bob_enc_keypair) sig_power = SigningPower(keypair=bob_sig_keypair) power_ups = [enc_power, sig_power] print("Creating the Charlie ...") charlie = Bob( is_me=True, federated_only=True, crypto_power_ups=power_ups, start_learning_now=True, abort_on_learning_error=True, known_nodes=[ursula], save_metadata=False, network_middleware=RestMiddleware(), ) print("Charlie = ", charlie) # Join policy generated by alice with open("policy-metadata.json", 'r') as f: policy_data = json.load(f) policy_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_data["policy_pubkey"])) alices_sig_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_data["alice_sig_pubkey"])) label = policy_data["label"].encode() print("The Charlie joins policy for label '{}'".format( label.decode("utf-8"))) charlie.join_policy(label, alices_sig_pubkey) return charlie, policy_pubkey, alices_sig_pubkey, label
def downloadFile(self, username, receipt, policy_info): hash = receipt['hash_key'] input = self.ipfs_gateway_api.cat(hash) enc_privkey, sig_privkey = self.reveal_private_keys(username) bob_enc_key = DecryptingKeypair(private_key=enc_privkey) bob_sig_keyp = SigningKeypair(private_key=sig_privkey) enc_power = DecryptingPower(keypair=bob_enc_key) sig_power = SigningPower(keypair=bob_sig_keyp) power_ups = [enc_power, sig_power] self.Bob = Bob( federated_only=True, crypto_power_ups=power_ups, start_learning_now=True, abort_on_learning_error=True, known_nodes=[self.ursula], save_metadata=False, network_middleware=RestMiddleware(), ) policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(policy_info["policy_pubkey"])) enrico = Enrico.from_public_keys( {SigningPower: UmbralPublicKey.from_bytes(bytes.fromhex(receipt['data_source_public_key']))}, policy_encrypting_key=policy_pubkey ) alice_pubkey_restored = UmbralPublicKey.from_bytes(base58.b58decode(policy_info['alice_sig_pubkey'])) self.Bob.join_policy(policy_info['label'].encode(), alice_pubkey_restored) data = msgpack.loads(input, raw=False) message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits']) message_kit = next(message_kits) retrieved_plaintexts = self.Bob.retrieve( message_kit, enrico=enrico, alice_verifying_key=alice_pubkey_restored, label=policy_info['label'].encode(), ) plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False) print(plaintext) decrypted_data = plaintext['data'] return decrypted_data
def reencrypt(): from nucypher.characters.lawful import Bob # TODO: Cache & Optimize reenc_request = ReencryptionRequest.from_bytes(request.data) hrac = reenc_request.hrac bob = Bob.from_public_keys(verifying_key=reenc_request.bob_verifying_key) log.info(f"Reencryption request from {bob} for policy {hrac}") # Right off the bat, if this HRAC is already known to be revoked, reject the order. if hrac in this_node.revoked_policies: return Response(response=f"Policy with {hrac} has been revoked.", status=HTTPStatus.UNAUTHORIZED) publisher_verifying_key = reenc_request.publisher_verifying_key # Bob bob_ip_address = request.remote_addr bob_verifying_key = bob.stamp.as_umbral_pubkey() bob_identity_message = f"[{bob_ip_address}] Bob({bytes(bob.stamp).hex()})" # Verify & Decrypt KFrag Payload try: verified_kfrag = this_node._decrypt_kfrag(reenc_request.encrypted_kfrag, hrac, publisher_verifying_key) except DecryptingKeypair.DecryptionFailed: # TODO: don't we want to record suspicious activities here too? return Response(response="EncryptedKeyFrag decryption failed.", status=HTTPStatus.FORBIDDEN) except InvalidSignature as e: message = f'{bob_identity_message} Invalid signature for KeyFrag: {e}.' log.info(message) # TODO (#567): bucket the node as suspicious return Response(message, status=HTTPStatus.UNAUTHORIZED) # 401 - Unauthorized except Exception as e: message = f'{bob_identity_message} Invalid EncryptedKeyFrag: {e}.' log.info(message) # TODO (#567): bucket the node as suspicious return Response(message, status=HTTPStatus.BAD_REQUEST) # Enforce Policy Payment # TODO: Accept multiple payment methods # TODO: Evaluate multiple reencryption prerequisites & enforce policy expiration paid = this_node.payment_method.verify(payee=this_node.checksum_address, request=reenc_request) if not paid: message = f"{bob_identity_message} Policy {bytes(hrac)} is unpaid." return Response(message, status=HTTPStatus.PAYMENT_REQUIRED) # Re-encrypt # TODO: return a sensible response if it fails (currently results in 500) response = this_node._reencrypt(kfrag=verified_kfrag, capsules=reenc_request.capsules) # Now, Ursula saves evidence of this workorder to her database... # Note: we give the work order a random ID to store it under. with datastore.describe(ReencryptionRequestModel, str(uuid.uuid4()), writeable=True) as new_request: new_request.bob_verifying_key = bob_verifying_key headers = {'Content-Type': 'application/octet-stream'} return Response(headers=headers, response=bytes(response))
def onRequestBuy(event): # print(event) user = event.args["buyer"] keys = masterfile_contract.functions.userKeys(user).call() tokenId = event.args["tokenId"] token = masterfile_contract.functions.tokenData(tokenId).call() uri = token[1] label = token[2] print(user) print(token) global globalStorage # Call token transfer # using fake policy id compiled_data = encode_abi(['bytes16', 'uint256', 'string', 'address[]'], [ Random.new().read(16), 432000, label, [ "0x9920328f8D239613cDfFea4578e37d843772738F", "0xf71C4fbb1D0a85ded90c58fF347a026E6b8146AC", "0xC11F4fAa477b1634369153c8654eEF581425AD15" ] ]) masterfile_contract.functions.safeTransferFrom( token[0], user, tokenId, 1, compiled_data).transact({'from': w3.eth.accounts[0]}) # Revoke old policy try: if globalStorage[uri]["policy"]: alice.revoke(globalStorage[uri]["policy"]) print("Policy Revoked") except: print("No Policy") # Distribute kfrags # try: print(keys) bob = Bob.from_public_keys(verifying_key=keys[0], encrypting_key=keys[1], federated_only=True) policy = alice.grant(bob, label=uri.encode(), m=2, n=3, expiration=maya.now() + timedelta(days=5)) temp = globalStorage[uri] temp["policy"] = policy globalStorage[uri] = temp # except: # print("policy exsists") policy.treasure_map_publisher.block_until_complete() print("Policy {} was created".format(label))
def post(self): keys = request.json['keys'] path = self.writeKeys(keys) password = request.json['password'] address = request.json['address'] passwd = PBKDF2(password, address.encode(), 20, count=30000, hmac_hash_module=SHA256).hex() keyring = NucypherKeyring(account=address, keyring_root="./keys") keyring.unlock(password=passwd) bob = Bob(known_nodes=[self.URSULA], checksum_address=address, domain='lynx', keyring=keyring) enrico_key = request.json['enrico_key'] policy_key = request.json['policy_key'] data_source = Enrico.from_public_keys( verifying_key=bytes.fromhex(enrico_key), policy_encrypting_key=UmbralPublicKey.from_bytes( bytes.fromhex(policy_key))) ciphertext = request.json['ciphertext'] message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(ciphertext)) label = request.json['label'] alice_pubkey = request.json['alice_pubkey'] alice_pubkey_umbral = UmbralPublicKey.from_bytes( bytes.fromhex(alice_pubkey)) print("Retrieving...") retrieved_plaintexts = bob.retrieve( message_kit, label=label.encode(), enrico=data_source, alice_verifying_key=alice_pubkey_umbral) print("Retrieved.") result = retrieved_plaintexts[0].decode("utf-8") self.readAndDeleteKeys(address, keyring) #delete keys return result
def make_random_bob(): """Generates a random ephemeral Bob instance.""" bob_verifying_secret = UmbralPrivateKey.gen_key() bob_verifying_key = bob_verifying_secret.pubkey decrypting_secret = UmbralPrivateKey.gen_key() decrypting_key = decrypting_secret.pubkey bob = Bob.from_public_keys(verifying_key=bob_verifying_key, encrypting_key=decrypting_key, federated_only=False) return bob
def make_random_bob(): """Generates a random ephemeral Bob instance.""" bob_verifying_secret = SecretKey.random() bob_verifying_key = bob_verifying_secret.public_key() decrypting_secret = SecretKey.random() decrypting_key = decrypting_secret.public_key() bob = Bob.from_public_keys(verifying_key=bob_verifying_key, encrypting_key=decrypting_key, federated_only=False) print(f'Created BOB - {bytes(bob.stamp).hex()}') return bob
def __init__(self, signing_power_bytes: bytes, decrypt_power_bytes: bytes): self.signing_power_bytes = signing_power_bytes self.decrypt_power_bytes = decrypt_power_bytes powers_and_material = { DecryptingPower: UmbralPublicKey.from_bytes(decrypt_power_bytes), SigningPower: UmbralPublicKey.from_bytes(signing_power_bytes) } self.BOB = Bob.from_public_keys(powers_and_material, federated_only=True)
def test_anybody_can_encrypt(): """ Similar to anybody_can_verify() above; we show that anybody can encrypt. """ someone = Character(start_learning_now=False, federated_only=True, crypto_power_ups=[SigningPower]) bob = Bob(is_me=False, federated_only=True,) cleartext = b"This is Officer Rod Farva. Come in, Ursula! Come in Ursula!" ciphertext = someone.encrypt_for(bob, cleartext) assert ciphertext is not None
def grant_access(revoke_time, grant_time, days, m, n, recipient_pubkey_hex): label = b'vehicle-data' if int(revoke_time) >= int(grant_time): # either triggered at start or because revoke was executed return '' # Alicia now wants to share data associated with this label. # To do so, she needs the public key of the recipient. # In this example, we generate it on the fly (for demonstration purposes) bob_pubkeys = demo_keys.get_recipient_pubkeys("bob") powers_and_material = { DecryptingPower: bob_pubkeys['enc'], SigningPower: bob_pubkeys['sig'] } # We create a view of the Bob who's going to be granted access. bob = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) # Here are our remaining Policy details, such as: # - Policy duration policy_end_datetime = maya.now() + datetime.timedelta(days=int(days)) # - m-out-of-n: This means Alicia splits the re-encryption key in 5 pieces and # she requires Bob to seek collaboration of at least 3 Ursulas # TODO: Let's put just one Ursula for the moment. m, n = 1, 1 # With this information, Alicia creates a policy granting access to Bob. # The policy is sent to the NuCypher network. print("Creating access policy for the Doctor...") policy = alicia.grant(bob=bob, label=label, m=int(m), n=int(n), expiration=policy_end_datetime) print("Done!") # For the demo, we need a way to share with Bob some additional info # about the policy, so we store it in a JSON file policy_info = { "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": bytes(alicia.stamp).hex(), "label": label.decode("utf-8"), } with open(POLICY_INFO_FILE, 'w') as f: json.dump(policy_info, f) return 'Access granted to recipient with public key: {}!'.format( recipient_pubkey_hex)
def test_anybody_can_encrypt(): """ Similar to anybody_can_verify() above; we show that anybody can encrypt. """ someone = Character(start_learning_now=False, federated_only=True) bob = Bob(is_me=False, federated_only=True) cleartext = b"This is Officer Rod Farva. Come in, Ursula! Come in Ursula!" ciphertext, signature = someone.encrypt_for(bob, cleartext, sign=False) assert signature == constants.NOT_SIGNED assert ciphertext is not None
def createPolicy(): print('data') print(request.data.decode('utf-8')) print('data\n\n') json_data = json.loads(request.data.decode('utf-8')) bobName = json_data['bob'] label = json_data['label'] aliceFile = json_data['alice'] password = json_data['password'] label = label.encode() # Generating Alice alice_config = AliceConfiguration.from_configuration_file( filepath=aliceFile, known_nodes={ursula}, start_learning_now=False, ) print(alice_config) alice_config.attach_keyring() alice_config.keyring.unlock(password=password) alicia = alice_config(domains={'TEMPORARY_DOMAIN'}) alicia.start_learning_loop(now=True) # Generating Bob bobFilePath = os.path.join(os.getcwd(), 'bob/' + bobName + '.json') doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey) powers_and_material = { DecryptingPower: doctor_pubkeys['enc'], SigningPower: doctor_pubkeys['sig'] } print (powers_and_material) doctor_strange = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=10) # Generate Policy policy = alicia.grant(bob=doctor_strange, label=label, m=1, n=1, expiration=policy_end_datetime) print (policy.public_key.to_bytes().hex()) data = { 'done' : True } return jsonify(data)
def test_characters_use_keyring(tmpdir): keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS, password=INSECURE_DEVELOPMENT_PASSWORD, encrypting=True, rest=False, keyring_root=tmpdir) keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) Alice(federated_only=True, start_learning_now=False, keyring=keyring) Bob(federated_only=True, start_learning_now=False, keyring=keyring) Ursula(federated_only=True, start_learning_now=False, keyring=keyring, rest_host='127.0.0.1', rest_port=12345)