示例#1
0
def capsule_side_channel(enacted_policy):
    signing_keypair = SigningKeypair()
    data_source = DataSource(policy_pubkey_enc=enacted_policy.public_key,
                             signing_keypair=signing_keypair)
    message_kit, _signature = data_source.encapsulate_single_message(
        b"Welcome to the flippering.")
    return message_kit, data_source
示例#2
0
 def from_public_keys(cls, policy_public_key, datasource_public_key, label):
     umbral_public_key = UmbralPublicKey.from_bytes(datasource_public_key)
     return cls(
         policy_public_key,
         signing_keypair=SigningKeypair(public_key=umbral_public_key),
         label=label,
     )
示例#3
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
示例#4
0
 def __init__(self, policy_pubkey_enc, signing_keypair=NO_SIGNING_POWER, label=None) -> None:
     self.policy_pubkey = policy_pubkey_enc
     if signing_keypair is NO_SIGNING_POWER:
         signing_keypair = SigningKeypair()  # TODO: Generate signing key properly.  #241
     signing_power = SigningPower(keypair=signing_keypair)
     self.stamp = signing_power.get_signature_stamp()
     self.label = label
示例#5
0
def capsule_side_channel(enacted_federated_policy):
    data_source = DataSource(policy_pubkey_enc=enacted_federated_policy.public_key,
                             signing_keypair=SigningKeypair(),
                             label=enacted_federated_policy.label
                             )
    message_kit, _signature = data_source.encrypt_message(b"Welcome to the flippering.")
    return message_kit, data_source
示例#6
0
    def decrypt_for_policy(self, label: bytes, message_kit: UmbralMessageKit,
                           alice_pubkey: UmbralPublicKey,
                           bob_privkey: UmbralPrivateKey,
                           policy_pubkey: UmbralPublicKey,
                           data_source_pubkey: UmbralPublicKey):
        """
        Decrypt data for a Policy

        :param label: A label to represent the policies data
        :param message_kit: UmbralMessageKit
        :param alice_pubkey: Alice's public key
        :param bob_privkey: Bob's private key
        :param policy_pubkey: Policy's private key
        :param data_source_pubkey: DataSource's private key

        :return: The decrypted cleartext
        """
        print('decrypt_for_policy')
        # Initialize Bob
        BOB = Bob(crypto_power_ups=[
            SigningPower(keypair=SigningKeypair(bob_privkey)),
            EncryptingPower(keypair=EncryptingKeypair(bob_privkey))
        ],
                  known_nodes=(self.ursula, ),
                  federated_only=True,
                  always_be_learning=True)
        print('-=-=-=')
        print(label)
        print(bytes(alice_pubkey))
        # Bob joins the policy so that he can receive data shared on it
        BOB.join_policy(
            label,  # The label - he needs to know what data he's after.
            bytes(alice_pubkey
                  ),  # To verify the signature, he'll need Alice's public key.
            # verify_sig=True,  # And yes, he usually wants to verify that signature.
            # He can also bootstrap himself onto the network more quickly
            # by providing a list of known nodes at this time.
            node_list=[("localhost", 3601)])
        print('-=-=-=2')
        # Bob needs to reconstruct the DataSource.
        datasource_as_understood_by_bob = DataSource.from_public_keys(
            policy_public_key=policy_pubkey,
            datasource_public_key=bytes(data_source_pubkey),
            label=label)
        print('-=-=-=3')
        # NOTE: Not sure if I am doing something wrong or if this is missing
        #   from the serialized bytes
        message_kit.policy_pubkey = policy_pubkey

        # Now Bob can retrieve the original message.  He just needs the MessageKit
        # and the DataSource which produced it.
        cleartexts = BOB.retrieve(message_kit=message_kit,
                                  data_source=datasource_as_understood_by_bob,
                                  alice_verifying_key=alice_pubkey)
        print('-=-=-=4')
        return cleartexts[0]
示例#7
0
    def create_policy(self, label: bytes, alice_privkey: UmbralPrivateKey,
                      bob_pubkey: UmbralPublicKey, policy_expiration, m: int,
                      n: int):
        """
        Create a Policy with Alice granting Bob access to `label` DataSource

        :param label: A label to represent the policies data
        :param alice_privkey: Alice's private key
        :param bob_pubkey: Bob's public key
        :param policy_expiration: Datetime of policy expiration duration
        :param m: Minimum number of KFrags needed to rebuild ciphertext
        :param n: Total number of rekey shares to generate

        :return: The policy granted to Bob
        """
        # This is not how this should be implemented, but I am still figuring out
        # the keying material and why it is randomly generated when a character is
        # initialized, instead of being derived from the keys like the other powers
        # or explained how it should be stored.
        d = DelegatingPower()
        d.umbral_keying_material = UmbralKeyingMaterial.from_bytes(
            alice_privkey.to_bytes() + alice_privkey.get_pubkey().to_bytes())

        # Initialize Alice
        ALICE = Alice(
            crypto_power_ups=[
                SigningPower(keypair=SigningKeypair(alice_privkey)),
                EncryptingPower(keypair=EncryptingKeypair(alice_privkey)),
                # DelegatingPower
                d
            ],
            network_middleware=RestMiddleware(),
            known_nodes=(self.ursula, ),
            federated_only=True,
            always_be_learning=True)

        # Initialize Bob
        BOB = Bob(crypto_power_ups=[
            SigningPower(pubkey=bob_pubkey),
            EncryptingPower(pubkey=bob_pubkey)
        ],
                  known_nodes=(self.ursula, ),
                  federated_only=True,
                  always_be_learning=True)

        # Alice grants a policy for Bob
        policy = ALICE.grant(BOB,
                             label,
                             m=m,
                             n=n,
                             expiration=policy_expiration)

        return policy
示例#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
示例#9
0
TEMP_DOCTOR_CERTIFICATE_DIR = "{}/bob-certs".format(TEMP_DOCTOR_DIR)

# Remove previous demo files and create new ones
shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)
os.mkdir(TEMP_DOCTOR_DIR)
os.mkdir(TEMP_URSULA_CERTIFICATE_DIR)
os.mkdir(TEMP_DOCTOR_CERTIFICATE_DIR)

ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL,
                                         federated_only=True,
                                         minimum_stake=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(),
示例#10
0
    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)

# To create a Bob, we need the doctor's private keys previously generated.
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(
    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(),
示例#11
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,
              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,
                    )

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

    # DataSource becomes
    data_source = DataSource(policy_pubkey_enc=policy.public_key,
                             signing_keypair=SigningKeypair(),
                             label=label
                             )

    plaintext = b"What's your approach?  Mississippis or what?"
    message_kit, _signature = data_source.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=data_source,
                                        alice_verifying_key=alices_verifying_key)

    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=data_source,
                                   alice_verifying_key=alices_verifying_key)
示例#13
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)
示例#14
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()
示例#15
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
示例#16
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()