Exemple #1
0
    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)
Exemple #2
0
    def decrypt(self, label: bytes, message_kit: bytes) -> dict:
        """
        Character control endpoint to allow Alice to decrypt her own data.
        """

        from nucypher.characters.lawful import Enrico
        policy_encrypting_key = self.character.get_policy_encrypting_key_from_label(label)

        # TODO #846: May raise UnknownOpenSSLError and InvalidTag.
        message_kit = UmbralMessageKit.from_bytes(message_kit)

        enrico = Enrico.from_public_keys(
            verifying_key=message_kit.sender_verifying_key,
            policy_encrypting_key=policy_encrypting_key,
            label=label
        )

        plaintexts = self.character.decrypt_message_kit(
            message_kit=message_kit,
            data_source=enrico,
            label=label
        )

        response = {'cleartexts': plaintexts}
        return response
Exemple #3
0
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
Exemple #4
0
    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
Exemple #5
0
    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
Exemple #6
0
 def ensure_correct_sender(
         self,
         enrico: Optional["Enrico"] = None,
         policy_encrypting_key: Optional[UmbralPublicKey] = None):
     """
     Make sure that the sender of the message kit is set and corresponds to
     the given ``enrico``, or create it from the given ``policy_encrypting_key``.
     """
     if self.sender:
         if enrico and self.sender != enrico:
             raise ValueError(
                 f"Mismatched sender: the object has {self.sender}, provided {enrico}"
             )
     elif enrico:
         self.sender = enrico
     elif self.sender_verifying_key and policy_encrypting_key:
         # Well, after all, this is all we *really* need.
         from nucypher.characters.lawful import Enrico
         self.sender = Enrico.from_public_keys(
             verifying_key=self.sender_verifying_key,
             policy_encrypting_key=policy_encrypting_key)
     else:
         raise ValueError(
             "No information provided to set the message kit sender. "
             "Need eiter `enrico` or `policy_encrypting_key` to be given.")
Exemple #7
0
    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
Exemple #8
0
 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
Exemple #9
0
    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 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
Exemple #11
0
def reencrypt_data(data_filepath, policy_filename, listener):
    '''
    Now that the listener joined the policy in the NuCypher network,
    he can retrieve encrypted data which he can decrypt with his private key.
    '''

    with open(policy_filename, '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()

    track_encrypted_files = os.scandir(data_filepath)
    for track_segment_encrypted in track_encrypted_files:
        if not track_segment_encrypted.name.endswith('_encrypted'):
            continue
        with open(track_segment_encrypted, 'rb') as f:
            data = msgpack.load(f)

        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)

        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]
            file_name = track_segment_encrypted.path[:-10] + "_decrypted.mp3"

            with open(file_name, 'wb') as f:
                f.write(plaintext)

        except Exception as e:
            # We just want to know what went wrong and continue the demo
            traceback.print_exc()
Exemple #12
0
    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
Exemple #13
0
    def decrypt(self, label: bytes, message_kit: bytes):
        """
        Character control endpoint to allow Alice to decrypt her own data.
        """

        from nucypher.characters.lawful import Enrico

        policy_encrypting_key = self.character.get_policy_pubkey_from_label(
            label)
        message_kit = UmbralMessageKit.from_bytes(
            message_kit
        )  # TODO #846: 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)

        plaintexts = self.alice.decrypt_message_kit(message_kit=message_kit,
                                                    data_source=data_source,
                                                    label=label)

        return {'cleartexts': plaintexts}
#################################

alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(
    alices_pubkey_bytes_saved_for_posterity)

#######################################
# Encrypting and decrypting for bob A #
#######################################

try:
    cipherdata_A, _signature_A = enrico_A.encrypt_message(ipfs_bytes)
    print("Enrico_A encrypted data for Bob_A")
    data_source_public_key_A = bytes(enrico_A.stamp)

    enrico_as_understood_by_bob_A = Enrico.from_public_keys(
        verifying_key=data_source_public_key_A,
        policy_encrypting_key=policy_pubkey_A)

    print("Honest researcher is attempting to decrypted")
    decrypted_data_A = BOB_A.retrieve(
        message_kit=cipherdata_A,
        data_source=enrico_as_understood_by_bob_A,
        alice_verifying_key=alice_pubkey_restored_from_ancient_scroll,
        label=label_A)

    decrypted_data_A_0 = decrypted_data_A[0].decode('utf8').replace('\\"', '"')

    # pprint(decrypted_data_A_0)

    print("Honest researcher successfully decrypted!")
def decrypt_first_message():
    ###############
    # Back to Bob #
    ###############

    # Bob watches for the first claim to be made on alice about her health
    claim_added_filter = alice_claim_holder.events.ClaimAdded.createFilter(
        fromBlock=0x0, argument_filters={'topic': health_label_key})
    while True:
        events = claim_added_filter.get_all_entries()
        if events:
            break
        sleep(0.2)

    # From details of the event, Bob knows who made the claim.
    # That way, he can refer to the right DID in order to fetch right verification/signing keys.
    event = events[0]
    assert event.args.issuer == enrico_eth_address
    enrico_nucypher_signing_pub_key_as_seen_by_bob = enrico_proxy_account.functions.getData(
        nucypher_signing_key).call()

    # He uses Alice's Decentralized ID to get the policy's public key
    policy_pubkey_bytes_as_seen_by_bob = alice_proxy_account.functions.getData(
        health_label_key).call()
    policy_pubkey_as_seen_by_bob = UmbralPublicKey.from_bytes(
        policy_pubkey_bytes_as_seen_by_bob)

    # Now he can create an instance of Enrico
    enrico_as_understood_by_bob = Enrico.from_public_keys(
        verifying_key=enrico_nucypher_signing_pub_key_as_seen_by_bob,
        policy_encrypting_key=policy_pubkey_as_seen_by_bob)

    # From details of the event, Bob can also get URI of claim data.
    # From this intermediary data, he finds URI of cipher data.
    claim_content = ipfs_client.get_json(event.args.uri)
    clear_data_hex_digest_as_seen_by_bob = claim_content['clearDataHexDigest']
    cipher_ipfs_hash_as_seen_by_bob = claim_content['encryptedDataIPFSHash']

    # Bob can recreate the encrypted message kit from data found on-chain and on IPFS
    cipher_as_seen_by_bob = ipfs_client.cat(cipher_ipfs_hash_as_seen_by_bob)
    cipher_kit_as_seen_by_bob = UmbralMessageKit.from_bytes(
        cipher_as_seen_by_bob)

    # Now Bob can retrieve the original message, as he was granted access by Alice
    delivered_clear_data_list = bob.retrieve(
        message_kit=cipher_kit_as_seen_by_bob,
        data_source=enrico_as_understood_by_bob,
        alice_verifying_key=UmbralPublicKey.from_bytes(
            alice_nucypher_signing_pub_key_as_seen_by_bob),
        label=health_label)
    delivered_clear_data = delivered_clear_data_list[0]

    # Anytime, without any additional interaction with NuCypher network, Bob can efficiently
    # verify his own possession of the clear data by comparing its digest to the one stored on IPFS
    # as part of the claim intermediary data.
    assert keccak_256(delivered_clear_data).hexdigest(
    ) == clear_data_hex_digest_as_seen_by_bob

    # Bob indeed received data he was granted access to by Alice
    print("========== DATA RETRIEVED ==========")
    print(delivered_clear_data.decode())
        # In this case, the plaintext is a
        # single passage from James Joyce's Finnegan's Wake.
        # The matter of whether encryption makes the passage more or less readable
        # is left to the reader to determine.
        single_passage_ciphertext, _signature = enciro.encapsulate_single_message(plaintext)
        data_source_public_key = bytes(enciro.stamp)
        del enciro

        ###############
        # Back to Bob #
        ###############

        enrico_as_understood_by_bob = Enrico.from_public_keys(
            policy_public_key=policy.public_key,
            datasource_public_key=data_source_public_key,
            label=label
        )

        # Now Bob can retrieve the original message.
        alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(alices_pubkey_bytes_saved_for_posterity)
        delivered_cleartexts = BOB.retrieve(message_kit=single_passage_ciphertext,
                                        data_source=enrico_as_understood_by_bob,
                                        alice_verifying_key=alice_pubkey_restored_from_ancient_scroll)

        # We show that indeed this is the passage originally encrypted by Enrico.
        assert plaintext == delivered_cleartexts[0]
        #print("Retrieved: {}".format(delivered_cleartexts[0]))
    return render_template('demodata.html')

if __name__ == '__main__':
Exemple #17
0
    enrico = Enrico(policy_encrypting_key=policy_pubkey)

    # In this case, the plaintext is a
    # single passage from James Joyce's Finnegan's Wake.
    # The matter of whether encryption makes the passage more or less readable
    # is left to the reader to determine.
    single_passage_ciphertext, _signature = enrico.encrypt_message(plaintext)
    data_source_public_key = bytes(enrico.stamp)
    del enrico

    ###############
    # Back to Bob #
    ###############

    enrico_as_understood_by_bob = Enrico.from_public_keys(
        verifying_key=data_source_public_key,
        policy_encrypting_key=policy_pubkey)

    # Now Bob can retrieve the original message.
    alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(
        alices_pubkey_bytes_saved_for_posterity)
    delivered_cleartexts = BOB.retrieve(
        message_kit=single_passage_ciphertext,
        data_source=enrico_as_understood_by_bob,
        alice_verifying_key=alice_pubkey_restored_from_ancient_scroll,
        label=label)

    # We show that indeed this is the passage originally encrypted by Enrico.
    assert plaintext == delivered_cleartexts[0]
    print("Retrieved: {}".format(delivered_cleartexts[0]))
Exemple #18
0
    enrico = Enrico(policy_encrypting_key=policy_pubkey)

    # In this case, the plaintext is a
    # single passage from James Joyce's Finnegan's Wake.
    # The matter of whether encryption makes the passage more or less readable
    # is left to the reader to determine.
    single_passage_ciphertext, _signature = enrico.encrypt_message(plaintext)
    data_source_public_key = bytes(enrico.stamp)
    del enrico

    ###############
    # Back to Bob #
    ###############

    enrico_as_understood_by_bob = Enrico.from_public_keys(
        {SigningPower: data_source_public_key},
        policy_encrypting_key=policy_pubkey)

    # Now Bob can retrieve the original message.
    alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(
        alices_pubkey_bytes_saved_for_posterity)
    delivered_cleartexts = BOB.retrieve(
        message_kit=single_passage_ciphertext,
        data_source=enrico_as_understood_by_bob,
        alice_verifying_key=alice_pubkey_restored_from_ancient_scroll,
        label=label)

    # We show that indeed this is the passage originally encrypted by Enrico.
    assert plaintext == delivered_cleartexts[0]
    sendMessage(encodeMessage(format(delivered_cleartexts[0])))
    #print("Retrieved: {}".format(delivered_cleartexts[0]))
Exemple #19
0
def createBobToResolveData(sub_uuid, sender, event_uuid, sub_private_key,
                           sub_signer_key, policy_pub_key, policy_sign_key,
                           label):
    SEEDNODE_URI = "127.0.0.1:10151"
    # TODO: path joins?
    TEMP_DOCTOR_DIR = "{}/doctor-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)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI,
                                             federated_only=True,
                                             minimum_stake=0)
    # doctor private key

    encdoctor = UmbralPrivateKey.from_bytes(bytes.fromhex(sub_private_key))
    signdoctor = UmbralPrivateKey.from_bytes(bytes.fromhex(sub_signer_key))

    bob_enc_keypair = DecryptingKeypair(private_key=encdoctor)
    bob_sig_keypair = SigningKeypair(private_key=signdoctor)
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Doctor ...")

    doctor = 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("Doctor = ", doctor)

    policy_pub_keys = UmbralPublicKey.from_bytes(bytes.fromhex(policy_pub_key))
    policy_sign_keys = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_sign_key))
    label = label.encode()

    print("The Doctor joins policy for label '{}'".format(
        label.decode("utf-8")))
    doctor.join_policy(label, policy_sign_keys)

    data = msgpack.load(open(event_uuid + ".msgpack", "rb"), raw=False)
    message_kits = UmbralMessageKit.from_bytes(data['data'])
    data_source = Enrico.from_public_keys(
        verifying_key=data['data_source'],
        policy_encrypting_key=policy_pub_keys)

    try:
        retrieved_plaintexts = doctor.retrieve(
            message_kits,
            label=label,
            enrico=data_source,
            alice_verifying_key=policy_sign_keys)

        plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

        # Now we can get the heart rate and the associated timestamp,
        # generated by the heart rate monitor.
        location_decrypted = plaintext['data_enc']
        print(location_decrypted)
    except Exception as e:
        # We just want to know what went wrong and continue the demo
        traceback.print_exc()

    return location_decrypted
Exemple #20
0
def decryptDelegated():

    json_data = json.loads(request.data.decode('utf-8'))
    bob_private_keys = json.loads(json_data['bobKeys'])
    policy_public_key = json_data['policy_public_key']
    alice_signing_key = json_data['alice_sig_pubkey']
    label = json_data['label']

    # username = json_data['username']

    message = json_data['message']
    data_source = json_data['data_source']

    data_source = bytes.fromhex(data_source)
    print (bob_private_keys['enc'])

    enc = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["enc"]))
    sig = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["sig"]))

    # signingPublic = sig.get_pubkey()
    # bobFilePath = os.path.join(os.getcwd(), 'bob/' + username + '.json')
    # doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey)
    # print (signingPublic == doctor_pubkeys['sig'])
    # print (signingPublic)
    # print (doctor_pubkeys['sig'])
    print ('\n\n\n')

    bob_enc_keypair = DecryptingKeypair(private_key=enc)
    bob_sig_keypair = SigningKeypair(private_key=sig)

    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    doctor = Bob(
        domains={'TEMPORARY_DOMAIN'},
        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()
    )

    policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(policy_public_key))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(alice_signing_key))
    label = label.encode()

    doctor.join_policy(label, alices_sig_pubkey)

    message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(message))

    print (message_kit == MessageKit)
    print (message_kit)
    print (MessageKit)
    print ('\n\n\n')

    data_source = Enrico.from_public_keys(
        {SigningPower: data_source},
        policy_encrypting_key=policy_pubkey
    )

    retrieved_plaintexts = doctor.retrieve(
        label=label,
        message_kit=message_kit,
        data_source=data_source,
        alice_verifying_key=alices_sig_pubkey
    )

    # the object to be sent back to front end

    # {
    #     "fileFieldCount": 2,
    #     "textFieldCount": 2,
    #     "files  (stringified)": {
    #         "fileKey1": "fileUrl1",
    #         "fileKey2": "fileUrl2"
    #     },
    #     "textFields (stringified)": {
    #         "age": "18",
    #         "name": "arvind"
    #     }
    #  }

    plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

    # the object from plaintext
    # data_obj = createDataObject(plaintext, json_data['label'])

    return jsonify(plaintext)
Exemple #21
0
def decrypt_article(article_instance):

    username = article_instance.author.username

    DATASOURCE_FILENAME = f"\
{article_instance.author.username}-\
{article_instance.title}-\
datasource-pubkey.msgpack"

    DATA_SOURCE_DIR = os.path.join(
        settings.BASE_DIR,
        'nucypher_utils',
        'nucypher_data',
    )

    with open(
        os.path.join(
            DATA_SOURCE_DIR, DATASOURCE_FILENAME
        ),
        "rb"
    ) as file:
        data = msgpack.load(file)

    data_source_public_key = data[b'data_source_public_key']

    cipher_text = data[b'kits']

    POLICY_FILENAME = "policy-metadata.json"

    POLICY_FILE = os.path.join(
        settings.BASE_DIR,
        'nucypher_utils',
        'nucypher_data',
        POLICY_FILENAME,
    )

    with open(POLICY_FILE, 'r') as f:
        policy_pubkey_data = json.load(f)

    policy_pubkey_string = policy_pubkey_data['policy_pubkey']

    policy_pubkey_bytes = unhexlify(policy_pubkey_string)
    policy_pubkey = keys.UmbralPublicKey.from_bytes(policy_pubkey_bytes)

    enrico_as_understood_by_bob = Enrico.from_public_keys(
        {SigningPower: data_source_public_key},
        policy_encrypting_key=policy_pubkey,
    )

    ALICE_CONFIG_DIR = os.path.join(
        settings.BASE_DIR,
        'nucypher_utils',
        'nucypher_data',
        'nucypher_char_configs',
        'stridon-demo-alice')

    ALICE_CONFIG_FILE = os.path.join(
        ALICE_CONFIG_DIR,
        "alice.config"
    )

    passphrase = "TEST_ALICE_PASSWORD"

    new_alice_config = AliceConfiguration.from_configuration_file(
            filepath=ALICE_CONFIG_FILE,
            network_middleware=RestMiddleware(),
            start_learning_now=False,
            save_metadata=False,
        )
    new_alice_config.keyring.unlock(password=passphrase)

    alice = new_alice_config()

    alice.start_learning_loop(now=True)

    alice_pubkey = keys.UmbralPublicKey.from_bytes(bytes(alice.stamp))

    BOB_CONFIG_DIR = os.path.join(
            settings.BASE_DIR,
            'nucypher_utils',
            'nucypher_data',
            'nucypher_char_configs',
            username)

    BOB_CONFIG_FILE = os.path.join(
        BOB_CONFIG_DIR,
        "bob.config"
    )

    new_premium_user = BobConfiguration.from_configuration_file(
        filepath=BOB_CONFIG_FILE,
        network_middleware=RestMiddleware(),
        start_learning_now=False,
        save_metadata=False,
    )

    new_premium_user.keyring.unlock(password=passphrase)
    premium_user = new_premium_user()

    policy_end_datetime = maya.now() + datetime.timedelta(days=5)

    label = b'stridon-premium-service'

    cipher_kit = kits.UmbralMessageKit.from_bytes(cipher_text)



    print("ALICE")
    print(alice.public_keys(SigningPower))
    print(alice.public_keys(DecryptingPower))
    print("PREMIUM_USER")
    print(premium_user.public_keys(SigningPower))
    print(premium_user.public_keys(DecryptingPower))

    try:
        delivered_cleartexts = premium_user.retrieve(
            message_kit=cipher_kit,
            data_source=enrico_as_understood_by_bob,
            alice_verifying_key=alice_pubkey,
            label=label
        )
        failed = False
        plain_text_article_content = delivered_cleartexts[0]
    except KeyError:
        plain_text_article_content = ''
        failed = True
    return (plain_text_article_content, failed)
Exemple #22
0
    bytes.fromhex(policy_data["alice_sig_pubkey"]))
label = policy_data["label"].encode()

print("The Doctor joins policy for label '{}'".format(label.decode("utf-8")))
doctor.join_policy(label, alices_sig_pubkey)

# Now that the Doctor joined the policy in the NuCypher network,
# he can retrieve encrypted data which he can decrypt with his private key.
# But first we need some encrypted data!
# Let's read the file produced by the heart monitor and unpack the MessageKits,
# which are the individual ciphertexts.
data = msgpack.load(open("heart_data.msgpack", "rb"), raw=False)
message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

# The doctor also needs to create a view of the Data Source from its public keys
data_source = Enrico.from_public_keys({SigningPower: data['data_source']},
                                      policy_encrypting_key=policy_pubkey)

# Now he can ask the NuCypher network to get a re-encrypted version of each MessageKit.
for message_kit in message_kits:
    try:
        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)

        # Now we can get the heart rate and the associated timestamp,
Exemple #23
0
def decryptDelegated():
    # Fetch Request Data
    # {
    #     "bobKeys": "{\"enc\": \"40f05590a27491caf37049366fefd43e46034e4308f4f1fd233c166bc3980ab4\", \"sig\": \"3bcf21d3cb160118b499a883023569c60476f8731bd9eade11016c5030c1ca5d\"}",
    #     "policy_public_key": "02aef01b40c0a62a9a1f650dd9a8381695e21a7b3826c748a5b64831aa0dd9862c",
    #     "alice_sig_pubkey": "036c5d361000e6fbf3c4a84c98f924a3206e8a72c758a67e8300b5bee111b5fa97",
    #     "label": "1stlabel",
    #     "message": "messagekit",
    #     "data_source": "03a38eef9fd09c9841585dea93791e139a3003d540539673c8c719af55e46c0c1b",
    # }
    json_data = json.loads(request.data.decode('utf-8'))
    bob_private_keys = json.loads(json_data['bobKeys'])
    policy_public_key = json_data['policy_public_key']
    alice_signing_key = json_data['alice_sig_pubkey']
    label = json_data['label']

    # username = json_data['username']

    message = json_data['message']
    data_source = json_data['data_source']

    data_source = bytes.fromhex(data_source)
    print (bob_private_keys['enc'])

    enc = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["enc"]))
    sig = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["sig"]))

    # signingPublic = sig.get_pubkey()
    # bobFilePath = os.path.join(os.getcwd(), 'bob/' + username + '.json')
    # doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey)
    # print (signingPublic == doctor_pubkeys['sig'])
    # print (signingPublic)
    # print (doctor_pubkeys['sig'])
    print ('\n\n\n')

    bob_enc_keypair = DecryptingKeypair(private_key=enc)
    bob_sig_keypair = SigningKeypair(private_key=sig)

    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    doctor = Bob(
        domains={'TEMPORARY_DOMAIN'},
        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()
    )

    policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(policy_public_key))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(alice_signing_key))
    label = label.encode()

    doctor.join_policy(label, alices_sig_pubkey)

    message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(message))

    print (message_kit == MessageKit)
    print (message_kit)
    print (MessageKit)
    print ('\n\n\n')

    data_source = Enrico.from_public_keys(
        {SigningPower: data_source},
        policy_encrypting_key=policy_pubkey
    )

    retrieved_plaintexts = doctor.retrieve(
        label=label,
        message_kit=message_kit,
        data_source=data_source,
        alice_verifying_key=alices_sig_pubkey
    )

    # the object to be sent back to front end

    # {
    #     "fileFieldCount": 2,
    #     "textFieldCount": 2,
    #     "files  (stringified)": {
    #         "fileKey1": "fileUrl1",
    #         "fileKey2": "fileUrl2"
    #     },
    #     "textFields (stringified)": {
    #         "age": "18",
    #         "name": "arvind"
    #     }
    #  }

    plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

    # the object from plaintext
    data_obj = createDataObject(plaintext, json_data['label'])


    return jsonify(data_obj)
Exemple #24
0
def run_doc():

    globalLogPublisher.addObserver(SimpleObserver())

    ######################
    # Boring setup stuff #
    ######################

    SEEDNODE_URL = 'localhost:11501'

    # TODO: path joins?
    TEMP_DOCTOR_DIR = "{}/doctor-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)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL,
                                             federated_only=True,
                                             minimum_stake=0)

    # To create a Bob, we need the doctor's private keys previously generated.

    doctor_keys = get_doctor_privkeys()

    bob_enc_keypair = DecryptingKeypair(private_key=doctor_keys["enc"])
    bob_sig_keypair = SigningKeypair(private_key=doctor_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 Doctor ...")

    doctor = 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("Doctor = ", doctor)

    # Let's join the policy generated by Alicia. We just need some info about it.
    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 Doctor joins policy for label '{}'".format(
        label.decode("utf-8")))
    doctor.join_policy(label, alices_sig_pubkey)

    # Now that the Doctor joined the policy in the NuCypher network,
    # he can retrieve encrypted data which he can decrypt with his private key.
    # But first we need some encrypted data!
    # Let's read the file produced by the heart monitor and unpack the MessageKits,
    # which are the individual ciphertexts.
    data = msgpack.load(open("heart_data.msgpack", "rb"), raw=False)
    message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

    # The doctor also needs to create a view of the Data Source from its public keys
    data_source = Enrico.from_public_keys({SigningPower: data['data_source']},
                                          policy_encrypting_key=policy_pubkey)

    # Now he can ask the NuCypher network to get a re-encrypted version of each MessageKit.
    for message_kit in message_kits:
        try:
            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)

            # Now we can get the heart rate and the associated timestamp,
            # generated by the heart rate monitor.
            heart_rate = plaintext['heart_rate']
            timestamp = maya.MayaDT(plaintext['timestamp'])

            # This code block simply pretty prints the heart rate info
            terminal_size = shutil.get_terminal_size().columns
            max_width = min(terminal_size, 120)
            columns = max_width - 12 - 27
            scale = columns / 40
            scaled_heart_rate = int(scale * (heart_rate - 60))
            retrieval_time = "Retrieval time: {:8.2f} ms".format(1000 *
                                                                 (end - start))
            line = ("-" * scaled_heart_rate) + "❤︎ ({} BPM)".format(heart_rate)
            line = line.ljust(max_width - 27, " ") + retrieval_time
            print(line)
        except Exception as e:
            # We just want to know what went wrong and continue the demo
            traceback.print_exc()
Exemple #25
0
    bytes.fromhex(policy_data["alice_sig_pubkey"]))
label = policy_data["label"].encode()

print("The Doctor joins policy for label '{}'".format(label.decode("utf-8")))
doctor.join_policy(label, alices_sig_pubkey)

# Now that the Doctor joined the policy in the NuCypher network,
# he can retrieve encrypted data which he can decrypt with his private key.
# But first we need some encrypted data!
# Let's read the file produced by the heart monitor and unpack the MessageKits,
# which are the individual ciphertexts.
data = msgpack.load(open("heart_data.msgpack", "rb"), raw=False)
message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

# The doctor also needs to create a view of the Data Source from its public keys
data_source = Enrico.from_public_keys(verifying_key=data['data_source'],
                                      policy_encrypting_key=policy_pubkey)

# Now he can ask the NuCypher network to get a re-encrypted version of each MessageKit.
for message_kit in message_kits:
    start = timer()
    retrieved_plaintexts = doctor.retrieve(
        message_kit,
        label=label,
        enrico=data_source,
        alice_verifying_key=alices_sig_pubkey)
    end = timer()

    plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

    # Now we can get the heart rate and the associated timestamp,
    # generated by the heart rate monitor.
Exemple #26
0
    def downloadFile(self, downloadFilename, recipient_privkeys, receipt,
                     policy_info):
        hash = receipt['hash_key']
        input = self.ipfs.cat(hash)

        ursula = Ursula.from_seed_and_stake_info(
            seed_uri=self.URSULA_SEEDNODE_URI,
            federated_only=True,
            minimum_stake=0)

        bob_enc_keypair = DecryptingKeypair(
            private_key=UmbralPrivateKey.from_bytes(
                bytes.fromhex(recipient_privkeys["enc"])))
        bob_sig_keypair = SigningKeypair(
            private_key=UmbralPrivateKey.from_bytes(
                bytes.fromhex(recipient_privkeys["sig"])))
        enc_power = DecryptingPower(keypair=bob_enc_keypair)
        sig_power = SigningPower(keypair=bob_sig_keypair)
        power_ups = [enc_power, sig_power]

        authorizedRecipient = 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(),
        )

        policy_pubkey = UmbralPublicKey.from_bytes(
            bytes.fromhex(policy_info["policy_pubkey"]))

        enrico_as_understood = Enrico.from_public_keys(
            {
                SigningPower:
                UmbralPublicKey.from_bytes(
                    bytes.fromhex(receipt['data_source_public_key']))
            },
            #{SigningPower: data_source_public_key},
            policy_encrypting_key=policy_pubkey)
        alice_pubkey_restored = UmbralPublicKey.from_bytes(
            (policy_info['alice_sig_pubkey']))
        authorizedRecipient.join_policy(policy_info['label'].encode(),
                                        alice_pubkey_restored)

        kit = UmbralMessageKit.from_bytes(input)

        delivered_cleartexts = authorizedRecipient.retrieve(
            message_kit=kit,
            data_source=enrico_as_understood,
            alice_verifying_key=alice_pubkey_restored,
            label=(policy_info['label'].encode()))

        #delivered_cleartexts = authorizedRecipient.retrieve(message_kit=kit,data_source=data_source,alice_verifying_key=alice_pubkey_restored, label=(policy_info['label'].encode())  )

        data = base64.b64decode(delivered_cleartexts[0])
        output = open('./' + downloadFilename, 'wb')
        output.write(data)
        output.close()