Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
 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
Ejemplo n.º 3
0
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(),
              domain=TEMPORARY_DOMAIN,
              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)
    bob.disenchant()
Ejemplo n.º 4
0
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 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
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
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
Ejemplo n.º 8
0
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 test_characters_use_keystore(temp_dir_path):
    keystore = Keystore.generate(password=INSECURE_DEVELOPMENT_PASSWORD,
                                 keystore_dir=temp_dir_path)
    keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
    alice = Alice(federated_only=True,
                  start_learning_now=False,
                  keystore=keystore)
    Bob(federated_only=True, start_learning_now=False, keystore=keystore)
    Ursula(federated_only=True,
           start_learning_now=False,
           keystore=keystore,
           rest_host=LOOPBACK_ADDRESS,
           rest_port=12345,
           db_filepath=tempfile.mkdtemp(),
           domain=TEMPORARY_DOMAIN)
    alice.disenchant(
    )  # To stop Alice's publication threadpool.  TODO: Maybe only start it at first enactment?
    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 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)
    a = 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,
           db_filepath=tempfile.mkdtemp())
    a.disenchant(
    )  # To stop Alice's publication threadpool.  TODO: Maybe only start it at first enactment?
Ejemplo n.º 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
Ejemplo n.º 13
0
 def post(self):
     keys = request.json['keys']
     password = request.json['password']
     address = request.json['address']
     alice_pubkey = request.json['alice_pubkey']
     label = request.json['label']
     path = self.writeKeys(keys)
     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)
     alice_pubkey_umbral = UmbralPublicKey.from_bytes(
         bytes.fromhex(alice_pubkey))
     bob.join_policy(label.encode(),
                     alice_verifying_key=alice_pubkey_umbral,
                     block=True)
     self.readAndDeleteKeys(address, keyring)  # delete keys
Ejemplo n.º 14
0
bob_privkeys = demo_keys.get_recipient_privkeys("bob")

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 Bob ...")

bob = 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("Bob = ", bob)

joined = list()


def get_layout():
    unique_id = 'bob'

    layout = html.Div([
        html.Div([
Ejemplo n.º 15
0
ALICE = Alice(network_middleware=RestMiddleware(),
              known_nodes=(URSULA,),
              federated_only=True,
              always_be_learning=True,
              known_certificates_dir=CERTIFICATE_DIR,
              )

# Here are our Policy details.
policy_end_datetime = maya.now() + datetime.timedelta(days=5)
m = 2
n = 3
label = b"secret/files/and/stuff"

# Alice grants to Bob.
BOB = Bob(known_nodes=(URSULA,),
          federated_only=True,
          always_be_learning=True,
          known_certificates_dir=CERTIFICATE_DIR)
ALICE.start_learning_loop(now=True)
policy = ALICE.grant(BOB, label, m=m, n=n,
                     expiration=policy_end_datetime)

# Alice puts her public key somewhere for Bob to find later...
alices_pubkey_bytes_saved_for_posterity = bytes(ALICE.stamp)

# ...and then disappears from the internet.
del ALICE
# (this is optional of course - she may wish to remain in order to create
# new policies in the future.  The point is - she is no longer obligated.

#####################
# some time passes. #
Ejemplo n.º 16
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)
def test_bob_joins_policy_and_retrieves(federated_alice,
                                        federated_ursulas,
                                        certificates_tempdir,
                                        ):
    # Let's partition Ursulas in two parts
    a_couple_of_ursulas = list(federated_ursulas)[:2]
    rest_of_ursulas = list(federated_ursulas)[2:]

    # Bob becomes
    bob = Bob(federated_only=True,
              domains={TEMPORARY_DOMAIN},
              start_learning_now=True,
              network_middleware=MockRestMiddleware(),
              abort_on_learning_error=True,
              known_nodes=a_couple_of_ursulas,
              )

    # Bob only knows a couple of Ursulas initially
    assert len(bob.known_nodes) == 2

    # Alice creates a policy granting access to Bob
    # Just for fun, let's assume she distributes KFrags among Ursulas unknown to Bob
    n = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK - 2
    label = b'label://' + os.urandom(32)
    contract_end_datetime = maya.now() + datetime.timedelta(days=5)
    policy = federated_alice.grant(bob=bob,
                                   label=label,
                                   m=3,
                                   n=n,
                                   expiration=contract_end_datetime,
                                   handpicked_ursulas=set(rest_of_ursulas),
                                   )

    assert bob == policy.bob
    assert label == policy.label

    # Now, Bob joins the policy
    bob.join_policy(label=label,
                    alice_verifying_key=federated_alice.stamp,
                    block=True)

    # In the end, Bob should know all the Ursulas
    assert len(bob.known_nodes) == len(federated_ursulas)

    # Enrico becomes
    enrico = Enrico(policy_encrypting_key=policy.public_key)

    plaintext = b"What's your approach?  Mississippis or what?"
    message_kit, _signature = enrico.encrypt_message(plaintext)

    alices_verifying_key = federated_alice.stamp.as_umbral_pubkey()

    # Bob takes the message_kit and retrieves the message within
    delivered_cleartexts = bob.retrieve(message_kit,
                                        enrico=enrico,
                                        alice_verifying_key=alices_verifying_key,
                                        label=policy.label,
                                        retain_cfrags=True)

    assert plaintext == delivered_cleartexts[0]

    # Bob tries to retrieve again, but without using the cached CFrags, it fails.
    with pytest.raises(TypeError):
        delivered_cleartexts = bob.retrieve(message_kit,
                                            enrico=enrico,
                                            alice_verifying_key=alices_verifying_key,
                                            label=policy.label)

    cleartexts_delivered_a_second_time = bob.retrieve(message_kit,
                                                      enrico=enrico,
                                                      alice_verifying_key=alices_verifying_key,
                                                      label=policy.label,
                                                      use_attached_cfrags=True)

    # Indeed, they're the same cleartexts.
    assert delivered_cleartexts == cleartexts_delivered_a_second_time

    # Let's try retrieve again, but Alice revoked the policy.
    failed_revocations = federated_alice.revoke(policy)
    assert len(failed_revocations) == 0

    # One thing to note here is that Bob *can* still retrieve with the cached CFrags, even though this Policy has been revoked.  #892
    _cleartexts = bob.retrieve(message_kit,
                               enrico=enrico,
                               alice_verifying_key=alices_verifying_key,
                               label=policy.label,
                               use_precedent_work_orders=True,
                               )
    assert _cleartexts == delivered_cleartexts  # TODO: 892

    # OK, but we imagine that the message_kit is fresh here.
    message_kit.capsule.clear_cfrags()

    with pytest.raises(Ursula.NotEnoughUrsulas):
        _cleartexts = bob.retrieve(message_kit,
                                   enrico=enrico,
                                   alice_verifying_key=alices_verifying_key,
                                   label=policy.label,
                                   )
# Alice gets policy keys #
##########################

policy_pubkey_A = ALICE.get_policy_encrypting_key_from_label(label_A)
policy_pubkey_D = ALICE.get_policy_encrypting_key_from_label(label_D)

######################################
# Creating our data consumers/Bobs   #
######################################
print(
    "Starting Bob researchers looking for patients to participate in their trials."
)
print("One researcher is malicious, one is honest!")
BOB_A = Bob(known_nodes=[ursula],
            domains={TEMPORARY_DOMAIN},
            network_middleware=RestMiddleware(),
            federated_only=True,
            start_learning_now=True,
            learn_on_same_thread=True)

BOB_B = Bob(known_nodes=[ursula],
            domains={TEMPORARY_DOMAIN},
            network_middleware=RestMiddleware(),
            federated_only=True,
            start_learning_now=True,
            learn_on_same_thread=True)

BOB_D = Bob(known_nodes=[ursula],
            domains={TEMPORARY_DOMAIN},
            network_middleware=RestMiddleware(),
            federated_only=True,
            start_learning_now=True,
def test_bob_joins_policy_and_retrieves(federated_alice,
                                        federated_ursulas,
                                        certificates_tempdir,
                                        ):
    # Let's partition Ursulas in two parts
    a_couple_of_ursulas = list(federated_ursulas)[:2]
    rest_of_ursulas = list(federated_ursulas)[2:]

    # Bob becomes
    bob = Bob(federated_only=True,
              domain=TEMPORARY_DOMAIN,
              start_learning_now=True,
              network_middleware=MockRestMiddleware(),
              abort_on_learning_error=True,
              known_nodes=a_couple_of_ursulas,
              )

    # Bob has only connected to - at most - 2 nodes.
    assert sum(node.verified_node for node in bob.known_nodes) <= 2

    # Alice creates a policy granting access to Bob
    # Just for fun, let's assume she distributes KFrags among Ursulas unknown to Bob
    n = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK - 2
    label = b'label://' + os.urandom(32)
    contract_end_datetime = maya.now() + datetime.timedelta(days=5)
    policy = federated_alice.grant(bob=bob,
                                   label=label,
                                   m=3,
                                   n=n,
                                   expiration=contract_end_datetime,
                                   handpicked_ursulas=set(rest_of_ursulas),
                                   )

    assert bob == policy.bob
    assert label == policy.label

    try:
        # Now, Bob joins the policy
        bob.join_policy(label=label,
                        alice_verifying_key=federated_alice.stamp,
                        block=True)
    except policy.treasure_map.NowhereToBeFound:
        maps = []
        for ursula in federated_ursulas:
            for map in ursula.treasure_maps.values():
                maps.append(map)
        if policy.treasure_map in maps:
            # This is a nice place to put a breakpoint to examine Bob's failure to join a policy.
            bob.join_policy(label=label,
                            alice_verifying_key=federated_alice.stamp,
                            block=True)
            pytest.fail(f"Bob didn't find map {policy.treasure_map} even though it was available.  Come on, Bob.")
        else:
            pytest.fail(f"It seems that Alice didn't publish {policy.treasure_map}.  Come on, Alice.")

    # In the end, Bob should know all the Ursulas
    assert len(bob.known_nodes) == len(federated_ursulas)

    # Enrico becomes
    enrico = Enrico(policy_encrypting_key=policy.public_key)

    plaintext = b"What's your approach?  Mississippis or what?"
    message_kit, _signature = enrico.encrypt_message(plaintext)

    alices_verifying_key = federated_alice.stamp.as_umbral_pubkey()

    # Bob takes the message_kit and retrieves the message within
    delivered_cleartexts = bob.retrieve(message_kit,
                                        enrico=enrico,
                                        alice_verifying_key=alices_verifying_key,
                                        label=policy.label,
                                        retain_cfrags=True)

    assert plaintext == delivered_cleartexts[0]

    # Bob tries to retrieve again, but without using the cached CFrags, it fails.
    with pytest.raises(TypeError):
        delivered_cleartexts = bob.retrieve(message_kit,
                                            enrico=enrico,
                                            alice_verifying_key=alices_verifying_key,
                                            label=policy.label)

    cleartexts_delivered_a_second_time = bob.retrieve(message_kit,
                                                      enrico=enrico,
                                                      alice_verifying_key=alices_verifying_key,
                                                      label=policy.label,
                                                      use_attached_cfrags=True)

    # Indeed, they're the same cleartexts.
    assert delivered_cleartexts == cleartexts_delivered_a_second_time

    # Let's try retrieve again, but Alice revoked the policy.
    failed_revocations = federated_alice.revoke(policy)
    assert len(failed_revocations) == 0

    # One thing to note here is that Bob *can* still retrieve with the cached CFrags, even though this Policy has been revoked.  #892
    _cleartexts = bob.retrieve(message_kit,
                               enrico=enrico,
                               alice_verifying_key=alices_verifying_key,
                               label=policy.label,
                               use_precedent_work_orders=True,
                               )
    assert _cleartexts == delivered_cleartexts  # TODO: 892

    # OK, but we imagine that the message_kit is fresh here.
    message_kit.capsule.clear_cfrags()

    with pytest.raises(Ursula.NotEnoughUrsulas):
        _cleartexts = bob.retrieve(message_kit,
                                   enrico=enrico,
                                   alice_verifying_key=alices_verifying_key,
                                   label=policy.label,
                                   )

    bob.disenchant()
Ejemplo n.º 20
0
    seed_nodes=[ursula_seed_node],
    learn_on_same_thread=True,
    federated_only=True,
    known_certificates_dir=CERTIFICATE_DIR,
)

# Here are our Policy details.
policy_end_datetime = maya.now() + datetime.timedelta(days=5)
m = 2
n = 3
label = b"secret/files/and/stuff"

# Alice grants to Bob.
BOB = Bob(seed_nodes=[ursula_seed_node],
          network_middleware=RestMiddleware(),
          federated_only=True,
          start_learning_now=True,
          learn_on_same_thread=True,
          known_certificates_dir=CERTIFICATE_DIR)

ALICE.start_learning_loop(now=True)

policy = ALICE.grant(BOB, label, m=m, n=n, expiration=policy_end_datetime)

# Alice puts her public key somewhere for Bob to find later...
alices_pubkey_bytes_saved_for_posterity = bytes(ALICE.stamp)

# ...and then disappears from the internet.
del ALICE
# (this is optional of course - she may wish to remain in order to create
# new policies in the future.  The point is - she is no longer obligated.
Ejemplo n.º 21
0
######################################

ALICE = Alice(network_middleware=RestMiddleware(),
              known_nodes=[ursula],
              learn_on_same_thread=True,
              federated_only=True)

# Alice can get the public key even before creating the policy.
# From this moment on, any Data Source that knows the public key
# can encrypt data originally intended for Alice, but that can be shared with
# any Bob that Alice grants access.
policy_pubkey = ALICE.get_policy_pubkey_from_label(label)

BOB = Bob(known_nodes=[ursula],
          network_middleware=RestMiddleware(),
          federated_only=True,
          start_learning_now=True,
          learn_on_same_thread=True)

ALICE.start_learning_loop(now=True)

policy = ALICE.grant(BOB, label, m=m, n=n, expiration=policy_end_datetime)

assert policy.public_key == policy_pubkey

# Alice puts her public key somewhere for Bob to find later...
alices_pubkey_bytes_saved_for_posterity = bytes(ALICE.stamp)

# ...and then disappears from the internet.
del ALICE
Ejemplo n.º 22
0
print("\n************** Setup **************\n")

####################
# NuCypher Network #
####################

L1_NETWORK = 'mainnet'  # or 'ibex'
L2_NETWORK = 'polygon'  # or 'mumbai'

#####################
# Bob the BUIDLer  ##
#####################

# Then, there was bob. Bob learns about the
# rest of the network from the seednode.
bob = Bob(domain=L1_NETWORK)

# Bob puts his public keys somewhere alice can find them.
verifying_key = bob.public_keys(SigningPower)
encrypting_key = bob.public_keys(DecryptingPower)

######################################
# Alice, the Authority of the Policy #
######################################

# Connect to the ethereum provider.
connect_web3_provider(eth_provider_uri=L1_PROVIDER)
# Connect to the layer 2 provider.
connect_web3_provider(eth_provider_uri=L2_PROVIDER)

# Setup and unlock alice's ethereum wallet.
Ejemplo n.º 23
0
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(
    domain=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)

# 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 = PublicKey.from_bytes(
    bytes.fromhex(policy_data["policy_pubkey"]))
alices_sig_pubkey = PublicKey.from_bytes(
    bytes.fromhex(policy_data["alice_sig_pubkey"]))
Ejemplo n.º 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()
Ejemplo n.º 25
0
def test_alices_powers_are_persistent(federated_ursulas, tmpdir):

    passphrase = TEST_URSULA_INSECURE_DEVELOPMENT_PASSWORD

    # Let's create an Alice from a Configuration.
    # This requires creating a local storage for her first.
    node_storage = LocalFileBasedNodeStorage(
        federated_only=True,
        character_class=Ursula, # Alice needs to store some info about Ursula
        known_metadata_dir=os.path.join(tmpdir, "known_metadata"),
    )

    alice_config = AliceConfiguration(
        config_root=os.path.join(tmpdir, "config_root"),
        node_storage=node_storage,
        auto_initialize=True,
        auto_generate_keys=True,
        passphrase=passphrase,
        is_me=True,
        network_middleware=MockRestMiddleware(),
        known_nodes=federated_ursulas,
        start_learning_now=False,
        federated_only=True,
        save_metadata=False,
        load_metadata=False
    )
    alice = alice_config(passphrase=passphrase)

    # We will save Alice's config to a file for later use
    alice_config_file = alice_config.to_configuration_file()

    # Let's save Alice's public keys too to check they are correctly restored later
    alices_verifying_key = alice.public_keys(SigningPower)
    alices_receiving_key = alice.public_keys(EncryptingPower)

    # Next, let's fix a label for all the policies we will create later.
    label = b"this_is_the_path_to_which_access_is_being_granted"

    # Even before creating the policies, we can know what will be its public key.
    # This can be used by DataSources to encrypt messages before Alice grants access to Bobs
    policy_pubkey = alice.get_policy_pubkey_from_label(label)

    # Now, let's create a policy for some Bob.
    m, n = 3, 4
    policy_end_datetime = maya.now() + datetime.timedelta(days=5)

    bob = Bob(federated_only=True,
              start_learning_now=False,
              network_middleware=MockRestMiddleware(),
              )

    bob_policy = alice.grant(bob, label, m=m, n=n, expiration=policy_end_datetime)

    assert policy_pubkey == bob_policy.public_key

    # ... and Alice and her configuration disappear.
    del alice
    del alice_config

    ###################################
    #        Some time passes.        #
    #               ...               #
    # (jmyles plays the Song of Time) #
    #               ...               #
    #       Alice appears again.      #
    ###################################

    # A new Alice is restored from the configuration file
    new_alice_config = AliceConfiguration.from_configuration_file(
        filepath=alice_config_file,
        network_middleware=MockRestMiddleware(),
        known_nodes=federated_ursulas,
        start_learning_now=False,
    )

    new_alice = new_alice_config(passphrase=passphrase)

    # First, we check that her public keys are correctly restored
    assert alices_verifying_key == new_alice.public_keys(SigningPower)
    assert alices_receiving_key == new_alice.public_keys(EncryptingPower)

    # Bob's eldest brother, Roberto, appears too
    roberto = Bob(federated_only=True,
                  start_learning_now=False,
                  network_middleware=MockRestMiddleware(),
                  )

    # Alice creates a new policy for Roberto. Note how all the parameters
    # except for the label (i.e., recipient, m, n, policy_end) are different
    # from previous policy
    m, n = 2, 5
    policy_end_datetime = maya.now() + datetime.timedelta(days=3)
    roberto_policy = new_alice.grant(roberto, label, m=m, n=n, expiration=policy_end_datetime)

    # Both policies must share the same public key (i.e., the policy public key)
    assert policy_pubkey == roberto_policy.public_key
Ejemplo n.º 26
0
def doctor_decrypt(hash_key):
    globalLogPublisher.addObserver(SimpleObserver())
    SEEDNODE_URL = 'localhost:11501'

    TEMP_DOCTOR_DIR = "{}/doctor-files".format(
        os.path.dirname(os.path.abspath(__file__)))
    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)

    from doctor_keys import get_doctor_privkeys

    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)

    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)

    ipfs_api = ipfsapi.connect()
    file = ipfs_api.get(hash_key)
    print(file)
    os.rename(hash_key, 'patient_details.msgpack')
    data = msgpack.load(open("patient_details.msgpack", "rb"), raw=False)
    message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

    data_source = DataSource.from_public_keys(
        policy_public_key=policy_pubkey,
        datasource_public_key=data['data_source'],
        label=label)
    complete_message = []
    for message_kit in message_kits:
        print(message_kit)
        try:
            start = timer()
            retrieved_plaintexts = doctor.retrieve(
                message_kit=message_kit,
                data_source=data_source,
                alice_verifying_key=alices_sig_pubkey)
            end = timer()
            plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)
            complete_message.append(plaintext)
            print(plaintext)
            #with open("details.json", "w") as write_file:
            #               json.dump(plaintext, write_file)
        except Exception as e:
            traceback.print_exc()
    with open("details.json", "w") as write_file:
        json.dump(complete_message, write_file)
    return complete_message
def test_bob_joins_policy_and_retrieves(federated_alice,
                                        federated_ursulas,
                                        certificates_tempdir,
                                        ):
    # Let's partition Ursulas in two parts
    a_couple_of_ursulas = list(federated_ursulas)[:2]
    rest_of_ursulas = list(federated_ursulas)[2:]

    # Bob becomes
    bob = Bob(federated_only=True,
              start_learning_now=True,
              network_middleware=MockRestMiddleware(),
              abort_on_learning_error=True,
              known_nodes=a_couple_of_ursulas,
              )

    # Bob only knows a couple of Ursulas initially
    assert len(bob.known_nodes) == 2

    # Alice creates a policy granting access to Bob
    # Just for fun, let's assume she distributes KFrags among Ursulas unknown to Bob
    n = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK - 2
    label = b'label://' + os.urandom(32)
    contract_end_datetime = maya.now() + datetime.timedelta(days=5)
    policy = federated_alice.grant(bob=bob,
                                   label=label,
                                   m=3,
                                   n=n,
                                   expiration=contract_end_datetime,
                                   handpicked_ursulas=set(rest_of_ursulas),
                                   )

    assert bob == policy.bob
    assert label == policy.label

    # Now, Bob joins the policy
    bob.join_policy(label=label,
                    alice_pubkey_sig=federated_alice.stamp,
                    block=True)

    # In the end, Bob should know all the Ursulas
    assert len(bob.known_nodes) == len(federated_ursulas)

    # Enrico becomes
    enrico = Enrico(policy_encrypting_key=policy.public_key)

    plaintext = b"What's your approach?  Mississippis or what?"
    message_kit, _signature = enrico.encrypt_message(plaintext)

    alices_verifying_key = federated_alice.stamp.as_umbral_pubkey()

    # Bob takes the message_kit and retrieves the message within
    delivered_cleartexts = bob.retrieve(message_kit=message_kit,
                                        data_source=enrico,
                                        alice_verifying_key=alices_verifying_key,
                                        label=policy.label)

    assert plaintext == delivered_cleartexts[0]

    # FIXME: Bob tries to retrieve again
    # delivered_cleartexts = bob.retrieve(message_kit=message_kit,
    #                                     data_source=enrico,
    #                                     alice_verifying_key=alices_verifying_key,
    #                                     label=policy.label)
    #
    # assert plaintext == delivered_cleartexts[0]

    # # Let's try retrieve again, but Alice revoked the policy.
    failed_revocations = federated_alice.revoke(policy)
    assert len(failed_revocations) == 0

    with pytest.raises(Ursula.NotEnoughUrsulas):
        _cleartexts = bob.retrieve(message_kit=message_kit,
                                   data_source=enrico,
                                   alice_verifying_key=alices_verifying_key,
                                   label=policy.label)
Ejemplo n.º 28
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)
def test_alices_powers_are_persistent(federated_ursulas, tmpdir):

    # Create a non-learning AliceConfiguration
    alice_config = AliceConfiguration(config_root=os.path.join(
        tmpdir, 'nucypher-custom-alice-config'),
                                      network_middleware=MockRestMiddleware(),
                                      known_nodes=federated_ursulas,
                                      start_learning_now=False,
                                      federated_only=True,
                                      save_metadata=False,
                                      reload_metadata=False)

    # Generate keys and write them the disk
    alice_config.initialize(password=INSECURE_DEVELOPMENT_PASSWORD)

    # Unlock Alice's keyring
    alice_config.keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)

    # Produce an Alice
    alice = alice_config()  # or alice_config.produce()

    # Save Alice's node configuration file to disk for later use
    alice_config_file = alice_config.to_configuration_file()

    # Let's save Alice's public keys too to check they are correctly restored later
    alices_verifying_key = alice.public_keys(SigningPower)
    alices_receiving_key = alice.public_keys(DecryptingPower)

    # Next, let's fix a label for all the policies we will create later.
    label = b"this_is_the_path_to_which_access_is_being_granted"

    # Even before creating the policies, we can know what will be its public key.
    # This can be used by Enrico (i.e., a Data Source) to encrypt messages
    # before Alice grants access to Bobs.
    policy_pubkey = alice.get_policy_encrypting_key_from_label(label)

    # Now, let's create a policy for some Bob.
    m, n = 3, 4
    policy_end_datetime = maya.now() + datetime.timedelta(days=5)

    bob = Bob(federated_only=True,
              start_learning_now=False,
              network_middleware=MockRestMiddleware())

    bob_policy = alice.grant(bob,
                             label,
                             m=m,
                             n=n,
                             expiration=policy_end_datetime)

    assert policy_pubkey == bob_policy.public_key

    # ... and Alice and her configuration disappear.
    del alice
    del alice_config

    ###################################
    #        Some time passes.        #
    #               ...               #
    # (jmyles plays the Song of Time) #
    #               ...               #
    #       Alice appears again.      #
    ###################################

    # A new Alice is restored from the configuration file
    new_alice_config = AliceConfiguration.from_configuration_file(
        filepath=alice_config_file,
        network_middleware=MockRestMiddleware(),
        known_nodes=federated_ursulas,
        start_learning_now=False,
    )

    # Alice unlocks her restored keyring from disk
    new_alice_config.attach_keyring()
    new_alice_config.keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
    new_alice = new_alice_config()

    # First, we check that her public keys are correctly restored
    assert alices_verifying_key == new_alice.public_keys(SigningPower)
    assert alices_receiving_key == new_alice.public_keys(DecryptingPower)

    # Bob's eldest brother, Roberto, appears too
    roberto = Bob(federated_only=True,
                  start_learning_now=False,
                  network_middleware=MockRestMiddleware())

    # Alice creates a new policy for Roberto. Note how all the parameters
    # except for the label (i.e., recipient, m, n, policy_end) are different
    # from previous policy
    m, n = 2, 5
    policy_end_datetime = maya.now() + datetime.timedelta(days=3)
    roberto_policy = new_alice.grant(roberto,
                                     label,
                                     m=m,
                                     n=n,
                                     expiration=policy_end_datetime)

    # Both policies must share the same public key (i.e., the policy public key)
    assert policy_pubkey == roberto_policy.public_key
Ejemplo n.º 30
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