def decrypt_data(self, data_source_public_key, data, policy_info): """ Decrypt data Args: data_source_public_key (bytes): data_source_public_key data (bytes): encrypted data policy_info (dict): dict containing policy_pubkey, alice_sig_pubkey and label keys Returns: retrieved_plaintexts (list): list of str """ policy_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_info["policy_pubkey"])) alice_sig_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_info["alice_sig_pubkey"])) label = policy_info["label"].encode() self.bob.join_policy(label, alice_sig_pubkey) message_kit = UmbralMessageKit.from_bytes(data) data_source = Enrico.from_public_keys( verifying_key=data_source_public_key, policy_encrypting_key=policy_pubkey) retrieved_plaintexts = self.bob.retrieve( message_kit, label=label, enrico=data_source, alice_verifying_key=alice_sig_pubkey) retrieved_plaintexts = [ x.decode('utf-8') for x in retrieved_plaintexts ] return retrieved_plaintexts
def retrieve(self, label: bytes, policy_encrypting_key: bytes, alice_verifying_key: bytes, message_kit: bytes, treasure_map: Union[bytes, str, 'TreasureMap'] = None): """ Character control endpoint for re-encrypting and decrypting policy data. """ from nucypher.characters.lawful import Enrico policy_encrypting_key = UmbralPublicKey.from_bytes( policy_encrypting_key) alice_verifying_key = UmbralPublicKey.from_bytes(alice_verifying_key) message_kit = UmbralMessageKit.from_bytes( message_kit ) # TODO #846: May raise UnknownOpenSSLError and InvalidTag. enrico = Enrico.from_public_keys( verifying_key=message_kit.sender_verifying_key, policy_encrypting_key=policy_encrypting_key, label=label) self.character.join_policy(label=label, alice_verifying_key=alice_verifying_key) plaintexts = self.character.retrieve( message_kit, enrico=enrico, alice_verifying_key=alice_verifying_key, label=label, treasure_map=treasure_map) response_data = {'cleartexts': plaintexts} 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 from_json(cls, data: str, federated=False): """ Deserializes the PolicyCredential from JSON. """ from nucypher.characters.lawful import Ursula cred_json = json.loads(data) alice_verifying_key = UmbralPublicKey.from_bytes( cred_json['alice_verifying_key'], decoder=bytes().fromhex) label = bytes().fromhex(cred_json['label']) expiration = maya.MayaDT.from_iso8601(cred_json['expiration']) policy_pubkey = UmbralPublicKey.from_bytes(cred_json['policy_pubkey'], decoder=bytes().fromhex) treasure_map = None if 'treasure_map' in cred_json: if federated: # I know know. TODO: WTF. 466 and just... you know... whatever. _MapClass = TreasureMap else: _MapClass = SignedTreasureMap treasure_map = _MapClass.from_bytes(bytes().fromhex( cred_json['treasure_map'])) return cls(alice_verifying_key, label, expiration, policy_pubkey, treasure_map)
def follow_treasure_map(self, hrac, using_dht=False): treasure_map = self.treasure_maps[hrac] number_of_known_treasure_ursulas = 0 if not using_dht: for ursula_interface_id in treasure_map: pubkey = UmbralPublicKey.from_bytes(ursula_interface_id) if pubkey in self.known_nodes: number_of_known_treasure_ursulas += 1 newly_discovered_nodes = {} nodes_to_check = iter(self.known_nodes.values()) while number_of_known_treasure_ursulas < treasure_map.m: try: node_to_check = next(nodes_to_check) except StopIteration: raise self.NotEnoughUrsulas( "Unable to follow the TreasureMap; we just don't know enough nodes to ask about this. Maybe try using the DHT instead." ) new_nodes = self.learn_about_nodes(node_to_check.ip_address, node_to_check.rest_port) for new_node_pubkey in new_nodes.keys(): if new_node_pubkey in treasure_map: number_of_known_treasure_ursulas += 1 newly_discovered_nodes.update(new_nodes) self.known_nodes.update(newly_discovered_nodes) return newly_discovered_nodes, number_of_known_treasure_ursulas else: for ursula_interface_id in self.treasure_maps[hrac]: pubkey = UmbralPublicKey.from_bytes(ursula_interface_id) if ursula_interface_id in self.known_nodes: # If we already know about this Ursula, # we needn't learn about it again. continue if using_dht: # TODO: perform this part concurrently. value = self.server.get_now(ursula_interface_id) # TODO: Make this much prettier header, signature, ursula_pubkey_sig, _hrac, ( port, interface, ttl) = dht_value_splitter(value, msgpack_remainder=True) if header != constants.BYTESTRING_IS_URSULA_IFACE_INFO: raise TypeError( "Unknown DHT value. How did this get on the network?" ) # TODO: If we're going to implement TTL, it will be here. self.known_nodes[ursula_interface_id] = \ Ursula.as_discovered_on_network( dht_port=port, dht_interface=interface, powers_and_keys=({SigningPower: ursula_pubkey_sig}) )
def decrypt(self, channel_reader: object) -> bytes: ''' Decrypt extsting message using ChannelReader instance :param BOB: :return: ''' policy_pubkey_restored = UmbralPublicKey.from_bytes( self.policy_pubkey_bytes) data_source_restored = Enrico.from_public_keys( {SigningPower: self.data_source_pubkey_bytes}, policy_encrypting_key=policy_pubkey_restored) channel_reader.BOB.join_policy(self.label_bytes, self.alice_pubkey_bytes) alices_sig_pubkey = UmbralPublicKey.from_bytes( bytes(self.alice_pubkey_bytes)) message_kit_object = UmbralMessageKit.from_bytes(self.kit_bytes) return channel_reader.BOB.retrieve( message_kit=message_kit_object, data_source=data_source_restored, alice_verifying_key=alices_sig_pubkey, label=self.label_bytes)
def __init__(self, character_flag: Union[ALICE, BOB], verifying_key: Union[UmbralPublicKey, bytes], encrypting_key: Optional[Union[UmbralPublicKey, bytes]] = None, nickname: Optional[Union[bytes, str]] = None): try: self.__character_class = self.__CARD_TYPES[bytes(character_flag)] except KeyError: raise ValueError(f'Unsupported card type {str(character_flag)}') self.__character_flag = character_flag if isinstance(verifying_key, bytes): verifying_key = UmbralPublicKey.from_bytes(verifying_key) self.__verifying_key = verifying_key # signing public key if isinstance(encrypting_key, bytes): encrypting_key = UmbralPublicKey.from_bytes(encrypting_key) self.__encrypting_key = encrypting_key # public key if isinstance(nickname, str): nickname = nickname.encode() self.__nickname = nickname self.__validate()
def decrypt(self, bob, item_cid, pol, sig, lab): policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(pol)) alices_sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(sig)) label = lab.encode() dat = self.ipfs_gateway_api.cat(item_cid) doctor = bob doctor.join_policy(label, alices_sig_pubkey) data = msgpack.loads(dat, raw=False) message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits']) data_source = Enrico.from_public_keys( {SigningPower: data['data_source']}, policy_encrypting_key=policy_pubkey ) message_kit = next(message_kits) start = timer() retrieved_plaintexts = doctor.retrieve( label=label, message_kit=message_kit, data_source=data_source, alice_verifying_key=alices_sig_pubkey ) end = timer() plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False) heart_rate = plaintext['heart_rate'] timestamp = maya.MayaDT(plaintext['timestamp']) terminal_size = shutil.get_terminal_size().columns max_width = min(terminal_size, 120) columns = max_width - 12 - 27 scale = columns / 40 retrieval_time = "Retrieval time: {:8.2f} ms".format(1000 * (end - start)) line = heart_rate# + " " + retrieval_time return line
def retrieve(self, label: bytes, policy_encrypting_key: bytes, alice_verifying_key: bytes, message_kit: bytes): """ Character control endpoint for re-encrypting and decrypting policy data. """ from nucypher.characters.lawful import Enrico policy_encrypting_key = UmbralPublicKey.from_bytes(policy_encrypting_key) alice_pubkey_sig = UmbralPublicKey.from_bytes(alice_verifying_key) message_kit = UmbralMessageKit.from_bytes(message_kit) # TODO: May raise UnknownOpenSSLError and InvalidTag. data_source = Enrico.from_public_keys({SigningPower: message_kit.sender_pubkey_sig}, policy_encrypting_key=policy_encrypting_key, label=label) self.bob.join_policy(label=label, alice_pubkey_sig=alice_pubkey_sig) plaintexts = self.bob.retrieve(message_kit=message_kit, data_source=data_source, alice_verifying_key=alice_pubkey_sig, label=label) response_data = {'cleartexts': plaintexts} return response_data
def _validate(self, value): try: UmbralPublicKey.from_bytes(value) except InvalidNativeDataTypes as e: raise InvalidInputData( f"Could not convert input for {self.name} to an Umbral Key: {e}" )
def reencrypt_segment(enc_data, policy_metadata, listener): policy_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_metadata["policy_pubkey"])) alices_sig_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_metadata["alice_sig_pubkey"])) label = policy_metadata["label"].encode() data = msgpack.loads(enc_data) message_kit = UmbralMessageKit.from_bytes((data[b'track_segment_data'])) data_source = Enrico.from_public_keys(verifying_key=data[b'data_source'], policy_encrypting_key=policy_pubkey) plaintext = None try: start = timer() retrieved_plaintexts = listener.retrieve( message_kit, label=label, enrico=data_source, alice_verifying_key=alices_sig_pubkey) end = timer() plaintext = retrieved_plaintexts[0] except Exception as e: # We just want to know what went wrong and continue the demo traceback.print_exc() return plaintext
def create_keyfrag(): if not request.json or not 'id' in request.json or request.json['id'] in keyfrags.keys(): abort(400) k_id = request.json['id'] show_debug("Storing key fragment with id: " + str(k_id)) keyfrags[k_id] = { 'capsule': pre.Capsule.from_bytes(binascii.unhexlify(request.json['capsule'].encode()), params), 'keyfrag': KFrag.from_bytes(binascii.unhexlify(request.json['keyfrag'].encode()), SECP256K1), 'delegating': UmbralPublicKey.from_bytes(binascii.unhexlify(request.json['delegating'].encode()), params), 'receiving': UmbralPublicKey.from_bytes(binascii.unhexlify(request.json['receiving'].encode()), params), 'verifying': UmbralPublicKey.from_bytes(binascii.unhexlify(request.json['verifying'].encode()), params), 'rekeyfrag': None } show_debug('-- Delegating:' + request.json['delegating']) show_debug('-- Receiving:' + request.json['receiving']) now = time.time()*1000 keyfrags[k_id]['capsule'].set_correctness_keys(delegating=keyfrags[k_id]['delegating'], receiving=keyfrags[k_id]['receiving'], verifying=keyfrags[k_id]['verifying']) keyfrags[k_id]['rekeyfrag'] = pre.reencrypt(kfrag=keyfrags[k_id]['keyfrag'], capsule=keyfrags[k_id]['capsule']) end = time.time()*1000 enc_tot = end-now show_debug("-- Re-encrypted key fragment with id: " + str(k_id)) return jsonify({'time': enc_tot}), 201
def test_kfrags(): vector_file = os.path.join('vectors', 'vectors_kfrags.json') try: with open(vector_file) as f: vector_suite = json.load(f) except OSError: raise 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 = [ KFrag.from_bytes(bytes.fromhex(json_kfrag['kfrag'])) for json_kfrag in vector_suite['vectors'] ] for kfrag in kfrags: assert kfrag.verify(signing_pubkey=verifying_key, delegating_pubkey=delegating_key, receiving_pubkey=receiving_key), \ 'Invalid KFrag {}'.format(kfrag.to_bytes().hex())
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_access(label, bob_pubkeys): bob_pub_keys = json.loads(bob_pubkeys) bobpubkeys = {} bobpubkeys["enc"] = UmbralPublicKey.from_bytes( bytes.fromhex(bob_pub_keys["enc"])) bobpubkeys["sig"] = UmbralPublicKey.from_bytes( bytes.fromhex(bob_pub_keys["sig"])) artist.grant_access_policy(label, bobpubkeys) return
def decrypt_for_policy(): """ input: { "label": "", "message_kit": "", "alice_pubkey": "", "bob_privkey": "", "policy_pubkey": "", "data_source_pubkey": "" } response: { "success": "", "cleartext": "", "err_msg": "" } """ result = {'success': False, 'cleartext': None, 'err_msg': None} try: j = json.loads(request.data.decode('utf-8')) # TODO: Check if the input is valid # Parse the input values label = j['label'].encode('utf-8') message_kit = UmbralMessageKit.from_bytes( base64.urlsafe_b64decode(j['message_kit'])) alice_pubkey = UmbralPublicKey.from_bytes( j['alice_pubkey'], decoder=base64.urlsafe_b64decode) bob_privkey = UmbralPrivateKey.from_bytes( j['bob_privkey'], decoder=base64.urlsafe_b64decode) policy_pubkey = UmbralPublicKey.from_bytes( j['policy_pubkey'], decoder=base64.urlsafe_b64decode) data_source_pubkey = UmbralPublicKey.from_bytes( j['data_source_pubkey'], decoder=base64.urlsafe_b64decode) # Encrypt plaintext for policy cleartext = api.decrypt_for_policy(label, message_kit, alice_pubkey, bob_privkey, policy_pubkey, data_source_pubkey) # Format the response data result['cleartext'] = base64.urlsafe_b64encode(cleartext).decode( 'utf8') result['success'] = True except Exception as e: result['success'] = False result['err_msg'] = str(e) # Create response response = jsonify(result) return response
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 get_users_public_keys(name, serialized=False): dirname = "accounts/" + name + "/" fname = dirname+"recipent.public.json" with open(fname) as data_file: data = json.load(data_file) enc_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(data["enc"])) sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(data["sig"])) print(enc_pubkey, sig_pubkey) if serialized: return (base58.b58encode(bytes.fromhex(data["enc"])).decode("utf-8"), base58.b58encode(bytes.fromhex(data["sig"])).decode("utf-8")) return (enc_pubkey, sig_pubkey)
def join_policy(listener, policy_metadata): # Let's join the policy generated by Alicia. We just need some info about it. policy_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_metadata["policy_pubkey"])) alices_sig_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_metadata["alice_sig_pubkey"])) label = policy_metadata["label"].encode() print("The Listener joins policy for label '{}'".format( label.decode("utf-8"))) listener.join_policy(label, alices_sig_pubkey) return label.decode("utf-8")
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 enrico(click_config, action, policy_encrypting_key, dry_run, http_port, message): """ Start and manage an "Enrico" character control HTTP server """ if not policy_encrypting_key: raise click.BadArgumentUsage('--policy-encrypting-key is required to start Enrico.') if not click_config.json_ipc and not click_config.quiet: click.secho(ENRICO_BANNER) policy_encrypting_key = UmbralPublicKey.from_bytes(bytes.fromhex(policy_encrypting_key)) ENRICO = Enrico(policy_encrypting_key=policy_encrypting_key) if click_config.json_ipc: ENRICO.controller.emitter = IPCStdoutEmitter(quiet=click_config.quiet) if action == 'run': # Forrest controller = ENRICO.make_web_controller() ENRICO.log.info('Starting HTTP Character Web Controller') return controller.start(http_port=http_port, dry_run=dry_run) elif action == 'encrypt': if not message: raise click.BadArgumentUsage('--message is a required flag to encrypt.') encryption_request = {'message': message} response = ENRICO.controller.encrypt_message(request=encryption_request) return response else: raise click.BadArgumentUsage
def create_policy(): """ input: { "label": "",- "alice_privkey": "", "bob_pubkey": "", "policy_expiration": "", "m": "", "n": "" } response: { "success": "", "policy_pubkey": "", "policy_expiration_date": "", "err_msg": "" } """ result = { 'success': False, 'policy_pubkey': None, 'policy_expiration_date': None, 'err_msg': None } try: j = json.loads(request.data.decode('utf-8')) # TODO: Check if the input is valid # Parse the input values label = j['label'].encode('utf-8') alice_privkey = UmbralPrivateKey.from_bytes( j['alice_privkey'], decoder=base64.urlsafe_b64decode) bob_pubkey = UmbralPublicKey.from_bytes( j['bob_pubkey'], decoder=base64.urlsafe_b64decode) policy_expiration = maya.now() + datetime.timedelta( days=int(j['policy_expiration'])) m = int(j['m']) n = int(j['n']) # Create the policy policy = api.create_policy(label, alice_privkey, bob_pubkey, policy_expiration, m, n) # Format the response result['policy_pubkey'] = base64.urlsafe_b64encode( policy.public_key.to_bytes()).decode('utf8') result['policy_expiration_date'] = str(policy_expiration) result['success'] = True except Exception as e: result['success'] = False result['err_msg'] = str(e) # Create response response = jsonify(result) return response
def from_public_keys(cls, policy_public_key, datasource_public_key, label): umbral_public_key = UmbralPublicKey.from_bytes(datasource_public_key) return cls( policy_public_key, signing_keypair=SigningKeypair(public_key=umbral_public_key), label=label, )
def _create_enrico(emitter, policy_encrypting_key): policy_encrypting_key = UmbralPublicKey.from_bytes( bytes.fromhex(policy_encrypting_key)) ENRICO = Enrico(policy_encrypting_key=policy_encrypting_key) ENRICO.controller.emitter = emitter # TODO: set it on object creation? Or not set at all? return ENRICO
def reencrypt_via_rest(id_as_hex): from nucypher.policy.models import WorkOrder # Avoid circular import arrangement_id = binascii.unhexlify(id_as_hex) work_order = WorkOrder.from_rest_payload(arrangement_id, request.data) log.info("Work Order from {}, signed {}".format(work_order.bob, work_order.receipt_signature)) with ThreadedSession(db_engine) as session: policy_arrangement = datastore.get_policy_arrangement(arrangement_id=id_as_hex.encode(), session=session) kfrag_bytes = policy_arrangement.kfrag # Careful! :-) verifying_key_bytes = policy_arrangement.alice_pubkey_sig.key_data # TODO: Push this to a lower level. kfrag = KFrag.from_bytes(kfrag_bytes) alices_verifying_key = UmbralPublicKey.from_bytes(verifying_key_bytes) cfrag_byte_stream = b"" for capsule, capsule_signature in zip(work_order.capsules, work_order.capsule_signatures): # This is the capsule signed by Bob capsule_signature = bytes(capsule_signature) # Ursula signs on top of it. Now both are committed to the same capsule. capsule_signed_by_both = bytes(stamp(capsule_signature)) capsule.set_correctness_keys(verifying=alices_verifying_key) cfrag = pre.reencrypt(kfrag, capsule, metadata=capsule_signed_by_both) log.info("Re-encrypting for {}, made {}.".format(capsule, cfrag)) signature = stamp(bytes(cfrag) + bytes(capsule)) cfrag_byte_stream += VariableLengthBytestring(cfrag) + signature # TODO: Put this in Ursula's datastore work_order_tracker.append(work_order) headers = {'Content-Type': 'application/octet-stream'} return Response(response=cfrag_byte_stream, headers=headers)
def retrieve(self, message_kit, data_source, alice_pubkey_sig): hrac = keccak_digest( bytes(alice_pubkey_sig) + self.stamp + data_source.label) treasure_map = self.treasure_maps[hrac] # First, a quick sanity check to make sure we know about at least m nodes. known_nodes_as_bytes = set([bytes(n) for n in self.known_nodes.keys()]) intersection = treasure_map.ids.intersection(known_nodes_as_bytes) if len(intersection) < treasure_map.m: raise RuntimeError( "Not enough known nodes. Try following the TreasureMap again." ) work_orders = self.generate_work_orders(hrac, message_kit.capsule) for node_id in self.treasure_maps[hrac]: node = self.known_nodes[UmbralPublicKey.from_bytes(node_id)] cfrags = self.get_reencrypted_c_frags(work_orders[bytes( node.stamp)]) message_kit.capsule.attach_cfrag(cfrags[0]) verified, delivered_cleartext = self.verify_from(data_source, message_kit, decrypt=True) if verified: return delivered_cleartext else: raise RuntimeError( "Not verified - replace this with real message.")
def __init__(self, pubkey: UmbralPublicKey = None, keypair: keypairs.Keypair = None, generate_keys_if_needed=True) -> None: if keypair and pubkey: raise ValueError( "Pass keypair or pubkey_bytes (or neither), but not both.") elif keypair: self.keypair = keypair else: # They didn't pass a keypair; we'll make one with the bytes or # UmbralPublicKey if they provided such a thing. if pubkey: try: public_key = pubkey.as_umbral_pubkey() except AttributeError: try: public_key = UmbralPublicKey.from_bytes(pubkey) except TypeError: public_key = pubkey self.keypair = self._keypair_class(public_key=public_key) else: # They didn't even pass a public key. We have no choice but to generate a keypair. self.keypair = self._keypair_class( generate_keys_if_needed=True)
def enrico(action, policy_encrypting_key, dry_run, http_port): """ Start and manage an "Enrico" character control HTTP server """ click.secho(ENRICO_BANNER.format(policy_encrypting_key)) if action == 'run': # Forest policy_encrypting_key = UmbralPublicKey.from_bytes(bytes.fromhex(policy_encrypting_key)) ENRICO = Enrico(policy_encrypting_key=policy_encrypting_key) # Enrico Control enrico_control = ENRICO.make_wsgi_app() click.secho("Starting Enrico Character Control...") click.secho(f"Enrico Verifying Key {bytes(ENRICO.stamp).hex()}", fg="green", bold=True) # Run if dry_run: return hx_deployer = HendrixDeploy(action="start", options={"wsgi": enrico_control, "http_port": http_port}) hx_deployer.run() # <--- Blocking Call to Reactor else: raise click.BadArgumentUsage
def revoke_arrangement(id_as_hex): """ REST endpoint for revoking/deleting a KFrag from a node. """ from nucypher.policy.collections import Revocation revocation = Revocation.from_bytes(request.data) log.info("Received revocation: {} -- for arrangement {}".format(bytes(revocation).hex(), id_as_hex)) try: with ThreadedSession(db_engine) as session: # Verify the Notice was signed by Alice policy_arrangement = datastore.get_policy_arrangement( id_as_hex.encode(), session=session) alice_pubkey = UmbralPublicKey.from_bytes( policy_arrangement.alice_verifying_key.key_data) # Check that the request is the same for the provided revocation if id_as_hex != revocation.arrangement_id.hex(): log.debug("Couldn't identify an arrangement with id {}".format(id_as_hex)) return Response(status_code=400) elif revocation.verify_signature(alice_pubkey): datastore.del_policy_arrangement( id_as_hex.encode(), session=session) except (NotFound, InvalidSignature) as e: log.debug("Exception attempting to revoke: {}".format(e)) return Response(response='KFrag not found or revocation signature is invalid.', status=404) else: log.info("KFrag successfully removed.") return Response(response='KFrag deleted!', status=200)
def _create_enrico(emitter, policy_encrypting_key): policy_encrypting_key = UmbralPublicKey.from_bytes( bytes.fromhex(policy_encrypting_key)) ENRICO = Enrico(policy_encrypting_key=policy_encrypting_key) ENRICO.controller.emitter = emitter return ENRICO