コード例 #1
0
ファイル: msg.py プロジェクト: MayankSur/FutureOfBlockChain
def generate_message(policy_pubkey,  msg_data, username, label):

    data_source = DataSource(policy_pubkey_enc=policy_pubkey,
                             label=label)

    data_source_public_key = bytes(data_source.stamp)

    now = time.time()

    kits = list()

    user_input = {
        'name' : username,
        'msg': msg_data,
        'timestamp': now,
    }

    plaintext = msgpack.dumps(user_input, use_bin_type=True)
    message_kit, _signature = data_source.encrypt_message(plaintext)

    kit_bytes = message_kit.to_bytes()
    kits.append(kit_bytes)

    data = {
        'data_source': data_source_public_key,
        'kits': kits,
    }

    final_msg = msgpack.dumps(data, use_bin_type=True)

    return final_msg
コード例 #2
0
ファイル: data_ipfs.py プロジェクト: manishvishnoi2/MedBlock
def encrypt_patient_data(policy_pubkey, data_fields,
                                label: bytes = DEFAULT_LABEL,
                                save_as_file: bool = False):
    data_source = DataSource(policy_pubkey_enc=policy_pubkey,
                             label=label)

    data_source_public_key = bytes(data_source.stamp)
    ipfs_api = ipfsapi.connect()

    kits = list()
    with open("Merkle_json.json", "r") as read_file:
            data = json.load(read_file)
    share=data_fields
    share_data = {}
    for i in share:
        share_data[i] = {'Value' : data[0][i]['Value'], 'Hash' : data[0][i]['Hash']}

    plaintext = msgpack.dumps(share_data, use_bin_type=True)
    message_kit, _signature = data_source.encrypt_message(plaintext)

    kit_bytes = message_kit.to_bytes()
    kits.append(kit_bytes)

    data = {
        'data_source': data_source_public_key,
        'kits': kits,
    }

    if save_as_file:
        with open(PATIENT_DETAIL, "wb") as file:
            msgpack.dump(data, file, use_bin_type=True)
    res = ipfs_api.add(PATIENT_DETAIL)
    return res
コード例 #3
0
ファイル: fixtures.py プロジェクト: tko-heyjude/nucypher
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
コード例 #4
0
def generate_heartbeat_data(gen_time, policy_pubkey_hex, last_heart_rate):
    if int(gen_time) == 0:
        # button has not been clicked as yet or interval triggered before click
        return None

    label = 'heart-data'

    policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(policy_pubkey_hex))
    if not cached_data_source:
        data_source = DataSource(policy_pubkey_enc=policy_pubkey, label=label)
        data_source_public_key = bytes(data_source.stamp)

        data = {
            'data_source_pub_key': data_source_public_key,
        }
        with open(DATA_SOURCE_INFO_FILE, "wb") as file:
            msgpack.dump(data, file, use_bin_type=True)
        cached_data_source.append(data_source)
    else:
        data_source = cached_data_source[0]

    if last_heart_rate is not None:
        last_heart_rate = int(last_heart_rate)
    else:
        last_heart_rate = 80

    heart_rate = random.randint(max(60, last_heart_rate - 5),
                                min(100, last_heart_rate + 5))

    plaintext = msgpack.dumps(heart_rate, use_bin_type=True)
    message_kit, _signature = data_source.encrypt_message(plaintext)
    kit_bytes = message_kit.to_bytes()

    timestamp = time.time()
    df = pd.DataFrame.from_dict({
        'Timestamp': [timestamp],
        'EncryptedData': [kit_bytes.hex()],
    })

    # add new heartbeat data
    db_conn = sqlite3.connect(DB_FILE)
    try:
        df.to_sql(name=DB_NAME, con=db_conn, index=False, if_exists='append')
        print("Added heart rate️ measurement to db:", timestamp, "-> ❤", heart_rate)
    finally:
        db_conn.close()

    return heart_rate
コード例 #5
0
def test_alice_can_decrypt(federated_alice):

    label = b"boring test label"

    policy_pubkey = federated_alice.get_policy_pubkey_from_label(label)

    data_source = DataSource(policy_pubkey_enc=policy_pubkey, label=label)

    message = b"boring test message"
    message_kit, signature = data_source.encrypt_message(message=message)

    cleartext = federated_alice.verify_from(stranger=data_source,
                                            message_kit=message_kit,
                                            signature=signature,
                                            decrypt=True)
    assert cleartext == message
コード例 #6
0
def generate_vehicular_data(gen_time, policy_pubkey_hex, cached_last_reading):
    if int(gen_time) == 0:
        # button has not been clicked as yet or interval triggered before click
        return None

    label = 'vehicle-data'

    policy_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_pubkey_hex))
    if not cached_data_source:
        data_source = DataSource(policy_pubkey_enc=policy_pubkey, label=label)
        data_source_public_key = bytes(data_source.stamp)

        data = {
            'data_source_pub_key': data_source_public_key,
        }
        with open(DATA_SOURCE_INFO_FILE, "wb") as file:
            msgpack.dump(data, file, use_bin_type=True)
        cached_data_source.append(data_source)
    else:
        data_source = cached_data_source[0]

    latest_reading = generate_new_reading(cached_last_reading)

    plaintext = msgpack.dumps(latest_reading, use_bin_type=True)
    message_kit, _signature = data_source.encrypt_message(plaintext)
    kit_bytes = message_kit.to_bytes()

    timestamp = time.time()
    df = pd.DataFrame.from_dict({
        'Timestamp': [timestamp],
        'EncryptedData': [kit_bytes.hex()],
    })

    # add new vehicle data
    db_conn = sqlite3.connect(DB_FILE)
    try:
        df.to_sql(name=DB_NAME, con=db_conn, index=False, if_exists='append')
        print("Added vehicle sensor readings to db:", timestamp, " -> ",
              latest_reading)
    finally:
        db_conn.close()

    return json.dumps(latest_reading)
コード例 #7
0
ファイル: heart_monitor.py プロジェクト: tko-heyjude/nucypher
def generate_heart_rate_samples(policy_pubkey,
                                label: bytes = DEFAULT_LABEL,
                                samples: int = 500,
                                save_as_file: bool = False):
    data_source = DataSource(policy_pubkey_enc=policy_pubkey,
                             label=label)

    data_source_public_key = bytes(data_source.stamp)

    heart_rate = 80
    now = time.time()

    kits = list()
    for _ in range(samples):
        # Simulated heart rate data
        # Normal resting heart rate for adults: between 60 to 100 BPM
        heart_rate = random.randint(max(60, heart_rate-5),
                                    min(100, heart_rate+5))
        now += 3

        heart_rate_data = {
            'heart_rate': heart_rate,
            'timestamp': now,
        }

        plaintext = msgpack.dumps(heart_rate_data, use_bin_type=True)
        message_kit, _signature = data_source.encrypt_message(plaintext)

        kit_bytes = message_kit.to_bytes()
        kits.append(kit_bytes)

    data = {
        'data_source': data_source_public_key,
        'kits': kits,
    }

    if save_as_file:
        with open(HEART_DATA_FILENAME, "wb") as file:
            msgpack.dump(data, file, use_bin_type=True)

    return data
コード例 #8
0
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)
コード例 #9
0
def reproduce_stored_session(policy_pubkey_bytes: bytes,
                             label: bytes = DEFAULT_LABEL,
                             save_as_file: bool = False,
                             send_by_mqtt: bool = False,
                             store_in_db: bool = False):

    policy_pubkey = UmbralPublicKey.from_bytes(policy_pubkey_bytes)

    data_source = DataSource(policy_pubkey_enc=policy_pubkey, label=label)

    data_source_public_key = bytes(data_source.stamp)

    # path of session database file
    sessionPath = RECORDED_CAR_SESSION

    if send_by_mqtt:
        # Connect to MQTT platform
        client = mqtt.Client()
        client.username_pw_set(MQTT_USERNAME, MQTT_PASSWD)
        client.connect(MQTT_HOST, MQTT_PORT, 60)

        # Communication is starting: send public key
        client.publish("/Alicia_Car_Data/public_key", pub_key_bytes)
        client.publish("/Alicia_Car_Data/data_source_public_key",
                       data_source_public_key)

    # Message kits list
    kits = list()
    try:
        # Connection to saved session database
        db = sqlite3.connect(sessionPath)
        tripCurs = db.cursor()
        gpsCurs = db.cursor()
        obdCurs = db.cursor()
        beacons_dataCurs = db.cursor()

        # Data Base cursor for beacons data table
        beacons_dataCurs.execute("SELECT * FROM beacons_data")
        # take the first beacon data row from table
        beacons_dataRow = beacons_dataCurs.fetchone()

        # everytime that engine stop and start during session saving, new trip is created
        for trip in tripCurs.execute("SELECT * FROM trip"):
            start = trip[1]
            end = trip[2]

            nextTime = None

            for gpsRow in gpsCurs.execute(
                    "SELECT * FROM gps WHERE time>=(?) AND time<(?)",
                (start, end)):
                # if this is not the first iteration...
                if nextTime != None:
                    currentTime = nextTime
                    nextTime = gpsRow[6]

                    # time difference between two samples
                    diff = nextTime - currentTime

                    # sleep the thread: simulating gps signal delay
                    #time.sleep(0.01)

                    # take the same sample from obd table
                    obdCurs.execute("SELECT * FROM obd WHERE time=(?)",
                                    (currentTime, ))
                    obdRow = obdCurs.fetchone()

                    # obtained information about OBDII & GPS from sessions database
                    temp = int(obdRow[0])
                    rpm = int(obdRow[1])
                    vss = int(obdRow[2])
                    maf = obdRow[3]
                    throttlepos = obdRow[4]
                    lat = gpsRow[0]
                    lon = gpsRow[1]
                    alt = gpsRow[2]
                    gpsSpeed = gpsRow[3]
                    course = int(gpsRow[4])
                    gpsTime = int(gpsRow[5])

                    # structure for generating msgpack
                    car_data = {
                        "carInfo": {
                            "engineOn": True,
                            "temp": temp,
                            "rpm": rpm,
                            "vss": vss,
                            "maf": maf,
                            "throttlepos": throttlepos,
                            "lat": lat,
                            "lon": lon,
                            "alt": alt,
                            "gpsSpeed": gpsSpeed,
                            "course": course,
                            "gpsTime": gpsTime
                        }
                    }

                    plaintext = msgpack.dumps(car_data, use_bin_type=True)
                    message_kit, _signature = data_source.encrypt_message(
                        plaintext)

                    kit_bytes = message_kit.to_bytes()
                    kits.append(kit_bytes)

                    if send_by_mqtt:
                        client.publish("/Alicia_Car_Data", kit_bytes)

                    if store_in_db:
                        df = pd.DataFrame.from_dict({
                            'Timestamp': [time.time()],
                            'EncryptedData': [kit_bytes.hex()],
                        })

                        # add new vehicle data
                        db_conn = sqlite3.connect(DB_FILE)
                        df.to_sql(name=DB_NAME,
                                  con=db_conn,
                                  index=False,
                                  if_exists='append')

                        print('Added vehicle sensor readings to db: ',
                              car_data)

                else:
                    nextTime = gpsRow[6]

    finally:
        if db:
            db.close()

        if send_by_mqtt:
            client.publish("/Alicia_Car_Data/end", "end")

        data = {
            'data_source': data_source_public_key,
            'kits': kits,
        }

        if save_as_file:
            with open(DATA_FILENAME, "wb") as file:
                msgpack.dump(data, file, use_bin_type=True)

        data_json = json.dumps(car_data)

        return data_json
コード例 #10
0
print("**************James Joyce's Finnegan's Wake**************")
print()
print("---------------------------------------------------------")

for counter, plaintext in enumerate(finnegans_wake):

    #########################
    # Enrico, the Encryptor #
    #########################
    enrico = Enrico(policy_pubkey_enc=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(
        policy_public_key=policy_pubkey,
        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)