Exemplo n.º 1
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
    def reveal_private_keys(self, username):
        private_keys = self.user_path + username + self.private_key_path
        
        with open(private_keys) 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"]))

        return enc_privkey, sig_privkey
Exemplo n.º 3
0
def create_policy():
    """
    input:
        {
            "label": "",-
            "alice_privkey": "",
            "bob_pubkey": "",
            "policy_expiration": "",
            "m": "",
            "n": ""
        }

    response:
        {
            "success": "",
            "policy_pubkey": "",
            "policy_expiration_date": "",
            "err_msg": ""
        }
    """
    result = {
        'success': False,
        'policy_pubkey': None,
        'policy_expiration_date': None,
        'err_msg': None
    }

    try:
        j = json.loads(request.data.decode('utf-8'))

        # TODO: Check if the input is valid

        # Parse the input values
        label = j['label'].encode('utf-8')
        alice_privkey = UmbralPrivateKey.from_bytes(
            j['alice_privkey'], decoder=base64.urlsafe_b64decode)
        bob_pubkey = UmbralPublicKey.from_bytes(
            j['bob_pubkey'], decoder=base64.urlsafe_b64decode)
        policy_expiration = maya.now() + datetime.timedelta(
            days=int(j['policy_expiration']))
        m = int(j['m'])
        n = int(j['n'])

        # Create the policy
        policy = api.create_policy(label, alice_privkey, bob_pubkey,
                                   policy_expiration, m, n)

        # Format the response
        result['policy_pubkey'] = base64.urlsafe_b64encode(
            policy.public_key.to_bytes()).decode('utf8')
        result['policy_expiration_date'] = str(policy_expiration)

        result['success'] = True
    except Exception as e:
        result['success'] = False
        result['err_msg'] = str(e)

    # Create response
    response = jsonify(result)
    return response
Exemplo n.º 4
0
 def __decrypt_keyfile(self, key_path: str) -> UmbralPrivateKey:
     """Returns plaintext version of decrypting key."""
     key_data = _read_keyfile(key_path, deserializer=self._private_key_serializer)
     wrap_key = _derive_wrapping_key_from_key_material(salt=key_data['wrap_salt'],
                                                       key_material=self.__derived_key_material)
     plain_umbral_key = UmbralPrivateKey.from_bytes(key_bytes=key_data['key'], wrapping_key=wrap_key)
     return plain_umbral_key
Exemplo n.º 5
0
def test_privkey_roundtrip(p):
    insecure_scrypt_cost = 5   # This is deliberately insecure, just to make it faster
    k = UmbralPrivateKey.gen_key()
    rt = UmbralPrivateKey.from_bytes(k.to_bytes(password=p, _scrypt_cost=insecure_scrypt_cost), 
                                     password=p, 
                                     _scrypt_cost=insecure_scrypt_cost)
    assert(k.get_pubkey() == rt.get_pubkey())
Exemplo n.º 6
0
def get_reseller_pubkeys(ethPk):
    try:
        reseller_privkey = UmbralPrivateKey.from_bytes(bytes.fromhex(ethPk))
    except IndexError:
        reseller_privkey = UmbralPrivateKey.gen_key()

    return reseller_privkey.get_pubkey();
Exemplo n.º 7
0
def test_private_key_serialization(random_ec_curvebn1):
    priv_key = random_ec_curvebn1
    umbral_key = UmbralPrivateKey(priv_key, default_params())

    encoded_key = umbral_key.to_bytes()

    decoded_key = UmbralPrivateKey.from_bytes(encoded_key)
    assert priv_key == decoded_key.bn_key
Exemplo n.º 8
0
def test_key_encoder_decoder(random_ec_curvebn1):
    priv_key = random_ec_curvebn1
    umbral_key = UmbralPrivateKey(priv_key, default_params())

    encoded_key = umbral_key.to_bytes(encoder=base64.urlsafe_b64encode)

    decoded_key = UmbralPrivateKey.from_bytes(encoded_key,
                                              decoder=base64.urlsafe_b64decode)
    assert decoded_key.to_bytes() == umbral_key.to_bytes()
Exemplo n.º 9
0
def decrypt_for_policy():
    """
    input:
        {
            "label": "",
            "message_kit": "",
            "alice_pubkey": "",
            "bob_privkey": "",
            "policy_pubkey": "",
            "data_source_pubkey": ""
        }

    response:
        {
            "success": "",
            "cleartext": "",
            "err_msg": ""
        }
    """
    result = {'success': False, 'cleartext': None, 'err_msg': None}

    try:
        j = json.loads(request.data.decode('utf-8'))

        # TODO: Check if the input is valid

        # Parse the input values
        label = j['label'].encode('utf-8')
        message_kit = UmbralMessageKit.from_bytes(
            base64.urlsafe_b64decode(j['message_kit']))
        alice_pubkey = UmbralPublicKey.from_bytes(
            j['alice_pubkey'], decoder=base64.urlsafe_b64decode)
        bob_privkey = UmbralPrivateKey.from_bytes(
            j['bob_privkey'], decoder=base64.urlsafe_b64decode)
        policy_pubkey = UmbralPublicKey.from_bytes(
            j['policy_pubkey'], decoder=base64.urlsafe_b64decode)
        data_source_pubkey = UmbralPublicKey.from_bytes(
            j['data_source_pubkey'], decoder=base64.urlsafe_b64decode)

        # Encrypt plaintext for policy
        cleartext = api.decrypt_for_policy(label, message_kit, alice_pubkey,
                                           bob_privkey, policy_pubkey,
                                           data_source_pubkey)

        # Format the response data
        result['cleartext'] = base64.urlsafe_b64encode(cleartext).decode(
            'utf8')

        result['success'] = True
    except Exception as e:
        result['success'] = False
        result['err_msg'] = str(e)

    # Create response
    response = jsonify(result)
    return response
Exemplo n.º 10
0
def create_keyfrag():
    if (not request.json or not 't' in request.json
            or not 'delegating_secret' in request.json
            or not 'receiving' in request.json
            or not 'signer_secret' in request.json):
        abort(400)
    threshold = request.json['t']

    show_debug(request.json['delegating_secret'])

    sk_a = UmbralPrivateKey.from_bytes(binascii.unhexlify(
        request.json['delegating_secret'].encode()),
                                       params=params)
    pk_b = UmbralPublicKey.from_bytes(
        binascii.unhexlify(request.json['receiving'].encode()), params)
    sign_a = UmbralPrivateKey.from_bytes(binascii.unhexlify(
        request.json['signer_secret'].encode()),
                                         params=params)
    signer_a = signing.Signer(private_key=sign_a)

    show_debug("Generating kfrags")
    now = time.time() * 1000
    kfrags = pre.generate_kfrags(delegating_privkey=sk_a,
                                 signer=signer_a,
                                 receiving_pubkey=pk_b,
                                 threshold=threshold,
                                 N=nodes_num)
    end = time.time() * 1000
    gen_tot = end - now
    show_debug("Generated key fragment in: " + str(gen_tot))

    show_debug("Distributing kfrags")
    k_id = request.json['id']
    payload = {
        'capsule': request.json['capsule'],
        'delegating': request.json['pk'],
        'receiving': request.json['receiving'],
        'verifying': binascii.hexlify(sign_a.get_pubkey().to_bytes()).decode()
    }
    ree_tot = distribute_key_fragments(k_id, kfrags, payload, threshold)
    show_debug("Distributed key fragments")

    return jsonify({'gen_time': gen_tot, 'ree_time': ree_tot}), 201
Exemplo n.º 11
0
def test_private_key_serialization_with_encryption(random_ec_curvebn1):
    priv_key = random_ec_curvebn1
    umbral_key = UmbralPrivateKey(priv_key, default_params())

    insecure_cost = 15  # This is deliberately insecure, just to make the tests faster
    encoded_key = umbral_key.to_bytes(password=b'test', 
                                      _scrypt_cost=insecure_cost)

    decoded_key = UmbralPrivateKey.from_bytes(encoded_key, 
                                              password=b'test', 
                                              _scrypt_cost=insecure_cost)
    assert priv_key == decoded_key.bn_key
Exemplo n.º 12
0
def _decrypt_umbral_key(wrapping_key: bytes, nonce: bytes,
                        encrypting_key_material: bytes) -> UmbralPrivateKey:
    """
    Decrypts an encrypted key with nacl's XSalsa20-Poly1305 algorithm (SecretBox).
    Returns a decrypted key as an UmbralPrivateKey.
    """
    try:
        decrypted_key = SecretBox(wrapping_key).decrypt(
            encrypting_key_material, nonce)
    except CryptoError:
        raise
    umbral_key = UmbralPrivateKey.from_bytes(decrypted_key)
    return umbral_key
Exemplo n.º 13
0
def decrypt():
    api = ipfsapi.connect('127.0.0.1', 5001)
    res = {}
    cfrags = list()
    if request.headers['Content-Type'] == 'application/json':
        account = request.json['account']
        ciphertexthex = request.json['ciphertext']
        b_ciphertext = bytes.fromhex(ciphertexthex)
        decryptkey = request.json['decryptkey']
        b_decryptkey = bytes.fromhex(decryptkey)
        deckey = UmbralPrivateKey.from_bytes(b_decryptkey)
        capsuleaddr = request.json['capsule']
        b_capsule_all = api.cat(capsuleaddr)
        splitarr1 = b_capsule_all.split(b'ZAtech')
        b_basic_capsule = splitarr1[0]
        capsule = Capsule.from_bytes(b_basic_capsule,
                                     UmbralParameters(Curve(714)))
        print("0")
        correctness_keys = splitarr1[1]
        splitarr2 = correctness_keys.split(b'ZBtech')
        delegating = UmbralPublicKey.from_bytes(splitarr2[0])
        receiving = UmbralPublicKey.from_bytes(splitarr2[1])
        verifying = UmbralPublicKey.from_bytes(splitarr2[2])

        # 用带入的参数capsule_all的各种byte,重现绑定correctness keys的capsule.
        capsule.set_correctness_keys(delegating=delegating,
                                     receiving=receiving,
                                     verifying=verifying)
        print("1")

        b_cfrag_all = splitarr1[2].split(b'ZCtech')
        for b_cfrag in b_cfrag_all:
            cfrags.append(CapsuleFrag.from_bytes(b_cfrag))
        for cfrag in cfrags:
            capsule.attach_cfrag(cfrag)
        print("2")
        print(capsule)
        print(capsule.get_correctness_keys())
        print(cfrags)
        cleartext = pre.decrypt(ciphertext=b_ciphertext,
                                capsule=capsule,
                                decrypting_key=deckey)
        print("3")

        res = {"cleartext": cleartext.decode("utf-8")}
        print("\nbob_cleartext: ")
        print(cleartext)
        return jsonify(res), {'Content-Type': 'application/json'}
    return
Exemplo n.º 14
0
def create_keys():
    doctor_private_key = ""
    doctor_public_hex = ""
    shelf = shelve.open('python/proxy/doctor_private_key')
    if 'privKey' in shelf:
        doctor_private_key = UmbralPrivateKey.from_bytes(
            bytes.fromhex(shelf['privKey']))
    else:
        doctor_private_key = keys.UmbralPrivateKey.gen_key()
        doctor_public_hex = doctor_private_key.to_bytes().hex()
        shelf["privKey"] = doctor_public_hex

    shelf.close()

    doctor_public_key = doctor_private_key.get_pubkey()
    doctor_public_hex = doctor_public_key.to_bytes().hex()
    return doctor_private_key
Exemplo n.º 15
0
def revoke_policy():
    """
    NOTE: This custom revoke hack is not working in the current nucypher version

    input:
        {
            "label": "",
            "alice_privkey": "",
            "bob_pubkey": ""
        }

    response:
        {
            "success": "",
            "err_msg": ""
        }
    """
    result = {'success': False, 'err_msg': None}

    try:
        j = json.loads(request.data.decode('utf-8'))

        # TODO: Check if the input is valid

        # Parse the input values
        label = j['label'].encode('utf-8')
        alice_privkey = UmbralPrivateKey.from_bytes(
            j['alice_privkey'], decoder=base64.urlsafe_b64decode)
        bob_pubkey = UmbralPublicKey.from_bytes(
            j['bob_pubkey'], decoder=base64.urlsafe_b64decode)

        # Revoke the policy
        policy = api.revoke_policy(label, alice_privkey, bob_pubkey)

        # Format the response

        result['success'] = True
    except Exception as e:
        result['success'] = False
        result['err_msg'] = str(e)

    # Create response
    response = jsonify(result)
    return response
Exemplo n.º 16
0
def _get_tls_hosting_power(host: str = None,
                           tls_certificate_filepath: str = None,
                           tls_private_key_filepath: str = None):
    # Pre-Signed
    if tls_certificate_filepath and tls_private_key_filepath:
        with open(tls_private_key_filepath, 'rb') as file:
            tls_private_key = UmbralPrivateKey.from_bytes(file.read())
        tls_hosting_keypair = HostingKeypair(
            curve=ec.SECP384R1,
            host=host,
            certificate_filepath=tls_certificate_filepath,
            private_key=tls_private_key)

    # Self-Sign
    else:
        tls_hosting_keypair = HostingKeypair(curve=ec.SECP384R1, host=host)

    tls_hosting_power = TLSHostingPower(keypair=tls_hosting_keypair, host=host)
    return tls_hosting_power
Exemplo n.º 17
0
def decrypt_r():
    if (not request.json or not 't' in request.json
            or not 'verifying' in request.json
            or not 'receiving' in request.json
            or not 'receiving_secret' in request.json):
        abort(400)
    threshold = request.json['t']
    verify_a = UmbralPublicKey.from_bytes(
        binascii.unhexlify(request.json['verifying'].encode()), params)
    pk_b = UmbralPublicKey.from_bytes(
        binascii.unhexlify(request.json['receiving'].encode()), params)
    sk_b = UmbralPrivateKey.from_bytes(binascii.unhexlify(
        request.json['receiving_secret'].encode()),
                                       params=params)
    pk_a = UmbralPublicKey.from_bytes(
        binascii.unhexlify(request.json['sender'].encode()), params)
    capsule = pre.Capsule.from_bytes(
        binascii.unhexlify(request.json['capsule'].encode()), params)
    k_id = request.json['id']
    ciphertext = binascii.unhexlify(request.json['ciphert'].encode())

    show_debug("Gathering cfrags")
    now = time.time() * 1000
    capsule.set_correctness_keys(delegating=pk_a,
                                 receiving=pk_b,
                                 verifying=verify_a)
    cfrags = gather_capsule_fragments(k_id, threshold)
    end = time.time() * 1000
    cfr_tot = end - now
    show_debug("Gathered capsule fragments in: " + str(cfr_tot))

    show_debug("Decrypting")
    now = time.time() * 1000
    plaintext_b = decrypt(cfrags, capsule, ciphertext, sk_b, threshold)
    end = time.time() * 1000
    dec_tot = end - now
    show_debug('Decrypted in (ms)= ' + str(dec_tot))

    return jsonify({
        'plain': plaintext_b.decode(),
        'cfr_time': cfr_tot,
        'dec_time': dec_tot
    }), 201
Exemplo n.º 18
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)
Exemplo n.º 19
0
def kfraggen():
    api = ipfsapi.connect('127.0.0.1', 5001)
    addrs = list()
    if request.headers['Content-Type'] == 'application/json':
        account = request.json['account']
        # 所有的传入参数都是hex key
        delegatekey = request.json['delegatekey']
        b_delegatekey = bytes.fromhex(delegatekey)
        dk = UmbralPrivateKey.from_bytes(b_delegatekey)

        # signer参数就是传入alice的另一个sk
        signersk = request.json['signersk']
        b_signersk = bytes.fromhex(signersk)
        signk = UmbralPrivateKey.from_bytes(b_signersk)
        signer = signing.Signer(signk)

        publickey = request.json['publickey']
        b_publickey = bytes.fromhex(publickey)
        bpk = UmbralPublicKey.from_bytes(b_publickey)

        threshold = request.json['threshold']
        N = request.json['N']

        # 测试写入库 error
        # cursor = conn.cursor()
        # sql = "insert into saved(name, delekey, signingkey, receiverpk) values('%s', '%s', '%s', '%s')"
        #       % (account, delegatekey, signersk, publickey)
        # try:
        #     # Execute the SQL statement
        #     cursor.execute(sql)
        # except Exception as e:
        #     print("Error: ", e)
        # cursor.close()

        kfrags = pre.generate_kfrags(delegating_privkey=dk,
                                     signer=signer,
                                     receiving_pubkey=bpk,
                                     threshold=threshold,
                                     N=N)
        for kf in kfrags:
            addrs.append(api.add_bytes(kf.to_bytes()))
        # for addr in addrs:
        #     print(addr)
        # # ipfs地址读取bytes
        # biarray = api.cat(addr)
        # print(biarray)
        #
        # # bytes转key
        # kfragobj = KFrag.from_bytes(biarray)
        # print(kfragobj)
        #
        # # key转bytes
        # bye = kfragobj.to_bytes()
        # print(bye)
        #
        # # bytes转str
        # kfraghex = biarray.hex()
        # print(kfraghex)
        #
        # # str转bytes
        # d = bytes.fromhex(kfraghex)
        # print(d)
        # print("\n")

        # N个frag的ipfs地址写入数据库,带account。
        # cursor = conn.cursor()~~~
        # for addr in addrs:
        # sql = "insert into XXX(name, address) values('%s', '%s')" % (account, addr)
        # try:
        #     # Execute the SQL statement
        #     cursor.execute(sql)
        # except Exception as e:
        #     print("Error: ", e)
        # cursor.close()

        return jsonify(addrs), {'Content-Type': 'application/json'}
    return
Exemplo n.º 20
0
config.set_default_curve()

#2
# Generate an Umbral key pair
# ---------------------------
# First, Let's generate two asymmetric key pairs for Alice:
# A delegating key pair and a Signing key pair.

alices_private_key = None
shelf = shelve.open('python/proxy/aliceKey')

if alices_private_key == None:
    alices_private_key = keys.UmbralPrivateKey.gen_key()
    priv_hex = alices_private_key.to_bytes().hex()
    shelf["privKey"] = priv_hex
alices_private_key = UmbralPrivateKey.from_bytes(
    bytes.fromhex(shelf["privKey"]))
shelf.close()

# alices_private_key = keys.UmbralPrivateKey.gen_key()
alices_public_key = alices_private_key.get_pubkey()
alices_signing_key = keys.UmbralPrivateKey.gen_key()
alices_verifying_key = alices_signing_key.get_pubkey()
alices_signer = signing.Signer(private_key=alices_signing_key)
#3
# Encrypt some data for Alice
# ---------------------------
# Now let's encrypt data with Alice's public key.
# Invocation of `pre.encrypt` returns both the `ciphertext`,
# and a `capsule`. Anyone with Alice's public key can perform
# this operation.
with open("python/proxy/23.jpg", "rb") as imageFile:
Exemplo n.º 21
0
# pprint(json.dumps(json.loads(str({"('delegating',)": alices_public_key})))
# pprint(json.dumps(json.loads(str(bobs_public_key)))
# pprint(f'{"delegating": {alices_public_key}}')
# pprint(f'{"receiving": {bobs_public_key}}')
# pprint(f'{"verifying": {alices_verifying_key}}')
# pprint(f"capsule: bob_capsule")
shelf = shelve.open('mydata')  # open for reading and writing, creating if nec
#shelf.update({'delegating':apk_hex})
shelf["delegating"] = apk_hex
shelf["privKey"] = priv_hex
shelf.close()

shelf = shelve.open('mydata')

pprint(shelf["delegating"])
priv_key_fromBytesFile = UmbralPrivateKey.from_bytes(
    bytes.fromhex(shelf["privKey"]))
key_fromBytesFile = UmbralPublicKey.from_bytes(
    bytes.fromhex(shelf["delegating"]))
pprint(key_fromBytesFile)
pprint(priv_key_fromBytesFile)
shelf.close()

my_dict = {'delegating': apk_hex}


def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary

def test_lifecycle_with_serialization(N,
                                      M,
                                      signing_mode,
                                      curve=default_curve()):
    """
    This test is a variant of test_simple_api, but with intermediate 
    serialization/deserialization steps, modeling how pyUmbral artifacts 
    (such as keys, ciphertexts, etc) will actually be used. 
    These intermediate steps are in between the different 'usage domains' 
    in NuCypher, namely, key generation, delegation, encryption, decryption by 
    Alice, re-encryption by Ursula, and decryption by Bob. 

    Manually injects UmbralParameters for multi-curve testing.
    """

    # Convenience method to avoid replicating key generation code
    def new_keypair_bytes():
        privkey = UmbralPrivateKey.gen_key(params=params)
        return privkey.to_bytes(), privkey.get_pubkey().to_bytes()

    ## SETUP
    params = UmbralParameters(curve=curve)

    delegating_privkey_bytes, delegating_pubkey_bytes = new_keypair_bytes()
    signing_privkey_bytes, signing_pubkey_bytes = new_keypair_bytes()
    receiving_privkey_bytes, receiving_pubkey_bytes = new_keypair_bytes()

    ## DELEGATION DOMAIN:
    ## Alice delegates decryption rights to some Bob by generating a set of
    ## KFrags, using her delegating private key and Bob's receiving public key

    delegating_privkey = UmbralPrivateKey.from_bytes(delegating_privkey_bytes,
                                                     params)
    signing_privkey = UmbralPrivateKey.from_bytes(signing_privkey_bytes,
                                                  params)
    receiving_pubkey = UmbralPublicKey.from_bytes(receiving_pubkey_bytes,
                                                  params)

    signer = Signer(signing_privkey)

    sign_delegating_key, sign_receiving_key = signing_mode

    kfrags = pre.generate_kfrags(delegating_privkey=delegating_privkey,
                                 receiving_pubkey=receiving_pubkey,
                                 threshold=M,
                                 N=N,
                                 signer=signer,
                                 sign_delegating_key=sign_delegating_key,
                                 sign_receiving_key=sign_receiving_key)

    kfrags_bytes = tuple(map(bytes, kfrags))

    del kfrags
    del signer
    del delegating_privkey
    del signing_privkey
    del receiving_pubkey
    del params

    ## ENCRYPTION DOMAIN ##

    params = UmbralParameters(curve=curve)

    delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes,
                                                   params)

    plain_data = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(delegating_pubkey, plain_data)
    capsule_bytes = bytes(capsule)

    del capsule
    del delegating_pubkey
    del params

    ## DECRYPTION BY ALICE ##

    params = UmbralParameters(curve=curve)

    delegating_privkey = UmbralPrivateKey.from_bytes(delegating_privkey_bytes,
                                                     params)
    capsule = pre.Capsule.from_bytes(capsule_bytes, params)
    cleartext = pre.decrypt(ciphertext, capsule, delegating_privkey)
    assert cleartext == plain_data

    del delegating_privkey
    del capsule
    del params

    ## RE-ENCRYPTION DOMAIN (i.e., Ursula's side)

    cfrags_bytes = list()
    for kfrag_bytes in kfrags_bytes:
        params = UmbralParameters(curve=curve)
        delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes,
                                                       params)
        signing_pubkey = UmbralPublicKey.from_bytes(signing_pubkey_bytes,
                                                    params)
        receiving_pubkey = UmbralPublicKey.from_bytes(receiving_pubkey_bytes,
                                                      params)

        capsule = pre.Capsule.from_bytes(capsule_bytes, params)
        capsule.set_correctness_keys(delegating=delegating_pubkey,
                                     receiving=receiving_pubkey,
                                     verifying=signing_pubkey)

        # TODO: use params instead of curve?
        kfrag = KFrag.from_bytes(kfrag_bytes, params.curve)

        assert kfrag.verify(signing_pubkey, delegating_pubkey,
                            receiving_pubkey, params)

        cfrag_bytes = bytes(pre.reencrypt(kfrag, capsule))
        cfrags_bytes.append(cfrag_bytes)

        del capsule
        del kfrag
        del params
        del delegating_pubkey
        del signing_pubkey
        del receiving_pubkey

    ## DECRYPTION DOMAIN (i.e., Bob's side)
    params = UmbralParameters(curve=curve)

    capsule = pre.Capsule.from_bytes(capsule_bytes, params)
    delegating_pubkey = UmbralPublicKey.from_bytes(delegating_pubkey_bytes,
                                                   params)
    signing_pubkey = UmbralPublicKey.from_bytes(signing_pubkey_bytes, params)
    receiving_privkey = UmbralPrivateKey.from_bytes(receiving_privkey_bytes,
                                                    params)
    receiving_pubkey = receiving_privkey.get_pubkey()

    capsule.set_correctness_keys(delegating=delegating_pubkey,
                                 receiving=receiving_pubkey,
                                 verifying=signing_pubkey)

    for cfrag_bytes in cfrags_bytes:
        # TODO: use params instead of curve?
        cfrag = CapsuleFrag.from_bytes(cfrag_bytes, params.curve)
        capsule.attach_cfrag(cfrag)

    reenc_cleartext = pre.decrypt(ciphertext, capsule, receiving_privkey)
    assert reenc_cleartext == plain_data
Exemplo n.º 23
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
Exemplo n.º 24
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)
Exemplo n.º 25
0
from umbral.keys import UmbralPrivateKey, UmbralPublicKey

from api import Api

policy_expiration = maya.now() + datetime.timedelta(days=365)
m = 1
n = 1

api = Api(node_meta_dir='../examples/examples-runtime-cruft')

# private_key1, public_key1 = api.gen_keypair()
# private_key2, public_key2 = api.gen_keypair()

private_key1 = UmbralPrivateKey.from_bytes(
    'DGgxOtqZOrqY-lh_E_L5H2YpNBoT3HEW6whMcVcqf5c=',
    decoder=base64.urlsafe_b64decode)
public_key1 = private_key1.get_pubkey()
print(bytes(public_key1))

private_key2 = UmbralPrivateKey.from_bytes(
    '8886EWu9cnGOCoZjNcI1SPEoyOiUTHBYwflfAA5YgCA=',
    decoder=base64.urlsafe_b64decode)
public_key2 = private_key2.get_pubkey()

print(private_key1.to_bytes())

label = 'test-2'.encode('utf-8')

policy = api.create_policy(label, private_key1, public_key2, policy_expiration,
                           m, n)
Exemplo n.º 26
0
    def downloadFile(self, downloadFilename, recipient_privkeys, receipt,
                     policy_info):
        hash = receipt['hash_key']
        input = self.ipfs.cat(hash)

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

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

        authorizedRecipient = Bob(
            is_me=True,
            federated_only=True,
            crypto_power_ups=power_ups,
            start_learning_now=True,
            abort_on_learning_error=True,
            known_nodes=[ursula],
            save_metadata=False,
            network_middleware=RestMiddleware(),
        )

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

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

        kit = UmbralMessageKit.from_bytes(input)

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

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

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