Example #1
0
def encrypt_and_sign(
        recipient_pubkey_enc: UmbralPublicKey,
        plaintext: bytes,
        signer: 'SignatureStamp',
        sign_plaintext: bool = True) -> Tuple[UmbralMessageKit, Signature]:
    if signer is not constants.DO_NOT_SIGN:
        # The caller didn't expressly tell us not to sign; we'll sign.
        if sign_plaintext:
            # Sign first, encrypt second.
            sig_header = constants.SIGNATURE_TO_FOLLOW
            signature = signer(plaintext)
            ciphertext, capsule = pre.encrypt(
                recipient_pubkey_enc, sig_header + signature + plaintext)
        else:
            # Encrypt first, sign second.
            sig_header = constants.SIGNATURE_IS_ON_CIPHERTEXT
            ciphertext, capsule = pre.encrypt(recipient_pubkey_enc,
                                              sig_header + plaintext)
            signature = signer(ciphertext)
        message_kit = UmbralMessageKit(
            ciphertext=ciphertext,
            capsule=capsule,
            sender_verifying_key=signer.as_umbral_pubkey(),
            signature=signature)
    else:
        # Don't sign.
        signature = sig_header = constants.NOT_SIGNED
        ciphertext, capsule = pre.encrypt(recipient_pubkey_enc,
                                          sig_header + plaintext)
        message_kit = UmbralMessageKit(ciphertext=ciphertext, capsule=capsule)

    return message_kit, signature
Example #2
0
    def _encrypt_credential_and_voter_short_private_key(
            self, credential: Tuple[UmbralPublicKey, Signer],
            private_key: UmbralPrivateKey) -> Dict[str, Tuple[bytes, Capsule]]:
        """encrypt credential and voter short private key

        Arguments:
            credential {Tuple[UmbralPublicKey, Signer]}
            private_key {UmbralPrivateKey}

        Returns:
            Dict[str, Tuple[bytes, Capsule]] -- need to save Capsule
        """
        credential_bytes = credential[0].to_bytes() + bytes(credential[1])
        private_key_bytes = private_key.to_bytes()

        (enc_credential, c_capsule) = encrypt(self.public_key,
                                              credential_bytes)

        (enc_private_key, p_capsule) = encrypt(self.public_key,
                                               private_key_bytes)

        voter_public_key = credential[0]

        for capsule in (c_capsule, p_capsule):
            capsule.set_correctness_keys(delegating=self.public_key,
                                         receiving=voter_public_key,
                                         verifying=self.verifying_key)

        return {
            "credential": (enc_credential, c_capsule),
            "private_key": (enc_private_key, p_capsule)
        }
Example #3
0
 def newUser(self, userAddress, firstName, lastName, dateOfBirth):
     userAddress = Web3.toChecksumAddress(userAddress)
     firstName, firstNameCapsule = pre.encrypt(self.publicKey, firstName)
     lastName, lastNameCapsule = pre.encrypt(self.publicKey, lastName)
     dateOfBirth, dateOfBirthCapsule = pre.encrypt(self.publicKey,
                                                   dateOfBirth)
     firstNameCapsule = firstNameCapsule.to_bytes()
     lastNameCapsule = lastNameCapsule.to_bytes()
     dateOfBirthCapsule = dateOfBirthCapsule.to_bytes()
     self.ehr.newUser(userAddress, firstNameCapsule, lastNameCapsule,
                      dateOfBirthCapsule, firstName, lastName, dateOfBirth)
Example #4
0
 def updateDisease(self, userAddress, diseaseTimestamp, message):
     userAddress = Web3.toChecksumAddress(userAddress)
     historyTimestamp = time.time()
     historyTimestamp = str(historyTimestamp).split('.')[0]
     historyTimestamp = bytes(historyTimestamp, encoding='utf-8')
     historyTimestamp, historyTimestampCapsule = pre.encrypt(
         self.publicKey, historyTimestamp)
     message, messageCapsule = pre.encrypt(self.publicKey, message)
     historyTimestamp = historyTimestamp.to_bytes()
     messageCapsule = messageCapsule.to_bytes()
     self.ehr.updateDisease(userAddress, historyTimestampCapsule,
                            messageCapsule, diseaseTimestamp,
                            historyTimestamp, message)
Example #5
0
 def addDisease(self, userAddress, diagnosis, therapy):
     userAddress = Web3.toChecksumAddress(userAddress)
     diseaseTimestamp = time.time()
     diseaseTimestamp = str(diseaseTimestamp).split('.')[0]
     diseaseTimestamp = bytes(diseaseTimestamp, encoding='utf-8')
     diagnosis, diagnosisCapsule = pre.encrypt(self.publicKey, diagnosis)
     therapy, therapyCapsule = pre.encrypt(self.publicKey, therapy)
     diseaseTimestamp, diseaseTimestampCapsule = pre.encrypt(
         self.publicKey, diseaseTimestamp)
     diagnosisCapsule = diagnosisCapsule.to_bytes()
     therapyCapsule = therapyCapsule.to_bytes()
     diseaseTimestampCapsule = diseaseTimestampCapsule.to_bytes()
     self.ehr.addDisease(userAddress, diseaseTimestampCapsule,
                         diagnosisCapsule, therapyCapsule, diseaseTimestamp,
                         diagnosis, therapy)
Example #6
0
def encrypt():
    # Get data from request
    json_data = json.loads(request.data.decode('utf-8'))
    data = json_data["hash"].encode(
        'utf-8')  #, json_data['alice_pubkey'], json_data['alice_privkey']

    alice_pubkey, alice_privkey = gen_alice()

    # Encrypt some data
    plaintext = data
    ciphertext, capsule = pre.encrypt(alice_pubkey, plaintext)

    alice_signing_privkey = keys.UmbralPrivateKey.gen_key()
    alice_signing_pubkey = alice_signing_privkey.get_pubkey()
    alice_signer = Signer(alice_signing_privkey)

    # Perform split-rekey and grant re-encryption policy
    alice_kfrags = pre.split_rekey(alice_privkey, alice_signer, bob_pubkey, 10,
                                   20)

    policy_id = mock_kms.grant(alice_kfrags)

    alice_pubkey.from_bytes

    response = {
        "ciphertext": bytes_to_string(ciphertext),
        "policy_id": policy_id,
        "capsule": bytes_to_string(capsule.to_bytes()),
        "alice_pubkey": bytes_to_string(alice_pubkey.to_bytes()),
        "alice_signing_pubkey":
        bytes_to_string(alice_signing_pubkey.to_bytes())
    }
    return jsonify(response)
def encrypt():
    if request.content_type.lower() != "application/json":
        abort(415)

    data = request.get_json()

    if "publicKey" in data and "plaintext" in data:
        try:
            start = time.perf_counter()
            publicKey = keys.UmbralPublicKey.from_hex(data["publicKey"])
            plaintext = data["plaintext"].encode("utf-8")
            ciphertext, capsule = pre.encrypt(publicKey, plaintext)
            end = time.perf_counter()

            time_stats_endpoints["encrypt"].append(end - start)

            return {
                "status": "ok",
                "ciphertext": ciphertext.hex(),
                "capsule": capsule.to_bytes().hex()
            }
        except Exception as e:
            return {"status": "error", "error": str(e)}

    abort(400)
Example #8
0
def generate_secret_key():
    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)

    # Generate Umbral keys for Bob.
    bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()
    plaintext = b'Proxy Re-Encryption is cool!'
    ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)

    # Decrypt data with Alice's private key.
    cleartext = pre.decrypt(ciphertext=ciphertext,
                            capsule=capsule,
                            decrypting_key=alices_private_key)
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                             signer=alices_signer,
                             receiving_pubkey=bobs_public_key,
                             threshold=10,
                             N=20)
    return jsonify(
        {
            "encrypted_result": f'{kfrags}'
        } 
    )
Example #9
0
def main(m, n, filenames):
    files = [open(filename, 'w') for filename in filenames]

    config.set_default_curve()

    alice_privkey = keys.UmbralPrivateKey.gen_key()
    alice_pubkey = alice_privkey.get_pubkey()

    bob_privkey = keys.UmbralPrivateKey.gen_key()
    bob_pubkey = bob_privkey.get_pubkey()

    mock_kms = MockNetwork()

    sys.stderr.write('Server with PID %s is ready to pipe messages.\n' % os.getpid())

    for line in sys.stdin:
        ciphertext, capsule = pre.encrypt(alice_pubkey, line.rstrip('\n').encode('utf8'))

        alice_kfrags = pre.split_rekey(alice_privkey, bob_pubkey, m, n)

        policy_id = mock_kms.grant(alice_kfrags)

        bob_cfrags = mock_kms.reencrypt(policy_id, capsule, m)

        bob_capsule = capsule
        for cfrag in bob_cfrags:
            bob_capsule.attach_cfrag(cfrag)

        decrypted = pre.decrypt(ciphertext, bob_capsule, bob_privkey, alice_pubkey)

        for file in files:
            file.write('%s\n' % decrypted.decode('utf8'))
            file.flush()

        mock_kms.revoke(policy_id)
Example #10
0
def alicebob_side_channel(alice):
    plaintext = b"Welcome to the flippering."
    ciphertext, capsule = pre.encrypt(alice.public_key(EncryptingPower),
                                      plaintext)
    return MessageKit(ciphertext=ciphertext,
                      capsule=capsule,
                      alice_pubkey=alice.public_key(EncryptingPower))
def test_alice_sends_fake_kfrag_to_ursula(N, M):

    priv_key_alice = keys.UmbralPrivateKey.gen_key()
    pub_key_alice = priv_key_alice.get_pubkey()

    priv_key_bob = keys.UmbralPrivateKey.gen_key()
    pub_key_bob = priv_key_bob.get_pubkey()

    plaintext = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(pub_key_alice, plaintext)

    cleartext = pre.decrypt(capsule, priv_key_alice, ciphertext)
    assert cleartext == plaintext

    k_frags = pre.split_rekey(priv_key_alice, pub_key_bob, M, N)

    # Alice tries to frame the first Ursula by sending her a random kFrag
    k_frags[0].bn_key = BigNum.gen_rand()

    for k_frag in k_frags:
        c_frag = pre.reencrypt(k_frag, capsule)
        capsule.attach_cfrag(c_frag)

    with pytest.raises(Exception):
        _ = pre.decrypt(capsule, priv_key_bob, ciphertext, pub_key_alice)
Example #12
0
def encrypt_and_save(file_content, filename, key):
    # Convert to UTF-8 bytes if not already in bytes format.
    try:
        if not isinstance(file_content, (bytes, bytearray)):
            file_content = str(file_content).encode('utf-8')

        # TODO: pass keys in as params.
        priv_key = keys.UmbralPrivateKey.gen_key()
        pub_key = priv_key.get_pubkey()

        # Encrypt file data with public key.
        ciphertext, capsule = pre.encrypt(pub_key, file_content)

        # Save file locally on the server.
        # TODO: can use external (nonlocal) service such as S3 for storing/retrieving encrypted files.
        bytes_written = 0
        with open("%s/%s" % (DEST_FOLDER, filename), 'wb') as f:
            bytes_written = f.write(ciphertext)

        capsule_written = 0
        with open("%s/capsule_%s" % (DEST_FOLDER, filename), 'wb') as f:
            capsule_written = f.write(str(capsule).encode())

        print('wrote %d encrypted bytes to %s, with %d capsule bytes' %
              (bytes_written, filename, capsule_written))
    except Exception as e:
        print(e)
Example #13
0
def test_decryption_fails_when_it_expects_a_proof_and_there_isnt(N, M, alices_keys, bobs_keys):
    """Manually injects umbralparameters for multi-curve testing."""

    delegating_privkey, signing_privkey = alices_keys
    delegating_pubkey = delegating_privkey.get_pubkey()
    signer = Signer(signing_privkey)
    priv_key_bob, pub_key_bob = bobs_keys

    plain_data = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(delegating_privkey.get_pubkey(), plain_data)

    kfrags = pre.split_rekey(delegating_privkey, signer, pub_key_bob, M, N)

    capsule.set_correctness_keys(delegating=delegating_privkey.get_pubkey(),
                                 receiving=pub_key_bob,
                                 verifying=signing_privkey.get_pubkey())
    for kfrag in kfrags[:M]:
        cfrag = pre.reencrypt(kfrag, capsule)
        capsule.attach_cfrag(cfrag)

    # Even thought we can successfully attach a CFrag, if the proof is lost
    # (for example, it is chopped off a serialized CFrag or similar), then decrypt
    # will still fail.
    cfrag.proof = None

    with pytest.raises(cfrag.NoProofProvided):
        _cleartext = pre.decrypt(ciphertext, capsule, priv_key_bob)
Example #14
0
def encrypt():
    if not request.json:
        abort(400)

    bob_public_key = request.json['recipient']
    pop_correct_public_key_hex = "03" + bob_public_key[-64:]
    print(pop_correct_public_key_hex)
    signedtext = request.json['data']

    alices_signing_key = keys.UmbralPrivateKey.gen_key()
    alices_verifying_key = alices_signing_key.get_pubkey()
    alices_signer = signing.Signer(private_key=alices_signing_key)

    #signedText

    bob = keys.UmbralPublicKey.from_bytes(
        bytes.fromhex(pop_correct_public_key_hex))
    ciphertext, capsule = pre.encrypt(bob, str.encode(signedtext))
    #grants access to Bob

    # kfrags = pre.generate_kfrags(delegating_privkey=alices_signing_key,
    # signer=alices_signer,
    # receiving_pubkey=bob,
    # threshold=10,
    # N=20)
    #, "capsule":capsule
    return jsonify(ciphertext=ciphertext.hex(),
                   capsule=capsule.to_bytes().hex()), 200
Example #15
0
def test_simple_api(N, M, curve=default_curve()):
    """Manually injects umbralparameters for multi-curve testing."""
    params = UmbralParameters(curve=curve)

    delegating_privkey = UmbralPrivateKey.gen_key(params=params)
    delegating_pubkey = delegating_privkey.get_pubkey()

    signing_privkey = UmbralPrivateKey.gen_key(params=params)
    signing_pubkey = signing_privkey.get_pubkey()
    signer = Signer(signing_privkey)

    receiving_privkey = UmbralPrivateKey.gen_key(params=params)
    receiving_pubkey = receiving_privkey.get_pubkey()

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

    cleartext = pre.decrypt(ciphertext, capsule, delegating_privkey)
    assert cleartext == plain_data

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

    kfrags = pre.split_rekey(delegating_privkey, signer, receiving_pubkey, M, N)

    for kfrag in kfrags:
        cfrag = pre.reencrypt(kfrag, capsule)
        capsule.attach_cfrag(cfrag)

    reenc_cleartext = pre.decrypt(ciphertext, capsule, receiving_privkey)
    assert reenc_cleartext == plain_data
Example #16
0
def encrypt():
	# Get data from request
	json_data = json.loads(request.data.decode('utf-8'))
	data, alice_pubkey, alice_privkey = json_data["hash"].encode(
		'utf-8'), json_data['alice_pubkey'], json_data['alice_privkey']

	alice_pubkey = string_to_bytes(alice_pubkey)
	alice_pubkey = keys.UmbralPublicKey.from_bytes(alice_pubkey)

	alice_privkey = string_to_bytes(alice_privkey)
	alice_privkey = keys.UmbralPrivateKey.from_bytes(alice_privkey)

	# Encrypt some data
	plaintext = data
	ciphertext, capsule = pre.encrypt(alice_pubkey, plaintext)

	# convert capsule to str
	capsule_id = str(uuid.uuid4())
	string_capsule = bytes_to_string(capsule.to_bytes())
	r.set(capsule_id, string_capsule)

	# capsule_id = mock_kms.putcapsule(capsule)

	response = {
		"ciphertext": bytes_to_string(ciphertext),
		"capsule_id": capsule_id,
	}

	return jsonify(response)
Example #17
0
def test_simple_api(N, M, curve=default_curve()):
    """Manually injects umbralparameters for multi-curve testing."""

    params = UmbralParameters(curve=curve)

    priv_key_alice = keys.UmbralPrivateKey.gen_key(params=params)
    pub_key_alice = priv_key_alice.get_pubkey()

    priv_key_bob = keys.UmbralPrivateKey.gen_key(params=params)
    pub_key_bob = priv_key_bob.get_pubkey()

    plain_data = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(pub_key_alice, plain_data, params=params)

    cleartext = pre.decrypt(ciphertext, capsule, priv_key_alice, params=params)
    assert cleartext == plain_data

    kfrags = pre.split_rekey(priv_key_alice, pub_key_bob, M, N, params=params)
    for kfrag in kfrags:
        cfrag = pre.reencrypt(kfrag, capsule, params=params)
        capsule.attach_cfrag(cfrag)

    reenc_cleartext = pre.decrypt(ciphertext,
                                  capsule,
                                  priv_key_bob,
                                  pub_key_alice,
                                  params=params)
    assert reenc_cleartext == plain_data
def test_capsule_as_dict_key(alices_keys):
    priv_key_alice, pub_key_alice = alices_keys
    plain_data = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(pub_key_alice, plain_data)

    # We can use the capsule as a key, and successfully lookup using it.
    some_dict = {capsule: "Thing that Bob wants to try per-Capsule"}
    assert some_dict[capsule] == "Thing that Bob wants to try per-Capsule"

    kfrags = pre.split_rekey(alices_keys.priv, alices_keys.pub, 1, 2)
    cfrag = pre.reencrypt(kfrags[0], capsule)
    capsule.attach_cfrag(cfrag)

    cfrag = pre.reencrypt(kfrags[1], capsule)
    capsule.attach_cfrag(cfrag)

    # Even if we activate the capsule, it still serves as the same key.
    cleartext = pre.decrypt(ciphertext, capsule, alices_keys.priv,
                            alices_keys.pub)
    assert some_dict[capsule] == "Thing that Bob wants to try per-Capsule"
    assert cleartext == plain_data

    # And if we change the value for this key, all is still well.
    some_dict[capsule] = "Bob has changed his mind."
    assert some_dict[capsule] == "Bob has changed his mind."
    assert len(some_dict.keys()) == 1
Example #19
0
    def get(self):
        sk_filename = "pk1"
        sk = keys.UmbralPrivateKey.gen_key()
        open("data/pk/" + sk_filename, "w").write(sk.to_bytes().hex())
        vk = sk.get_pubkey()
        user_id = vk.to_bytes().hex()
        timestamp = str(time.time())
        sk_sign = signing.Signer(sk)
        signature = sk_sign(timestamp.encode("utf8"))

        content = b"{}"
        ciphertext, capsule = pre.encrypt(vk, content)
        folder_size = "0"
        block_size = len(ciphertext)
        folder_hash = hashlib.sha1(ciphertext).hexdigest()
        folder_hash_binary = bin(int(folder_hash, 16))[2:].zfill(32 * 4)
        addr, groupid = yield get_group(folder_hash_binary)
        print("ciphertext", len(ciphertext), "capsule",
              capsule.to_bytes().hex())

        http_client = tornado.httpclient.AsyncHTTPClient()
        url = "http://%s:%s/user?user_id=%s&folder_hash=%s&block_size=%s&folder_size=%s&groupid=%s&capsule=%s&timestamp=%s&signature=%s" \
                % (tuple(addr)+(user_id, folder_hash, block_size, folder_size, groupid, capsule.to_bytes().hex(), timestamp, bytes(signature).hex()))
        try:
            response = yield http_client.fetch(url,
                                               method="POST",
                                               body=ciphertext)
        except Exception as e:
            print("Error: %s" % e)

        self.finish({"user_id": user_id})
Example #20
0
    def file_encrypt_and_upload(self,file):
        #file代表文件位置
        #该函数处理数据加密以及上传至ipfs以及区块链的功能
        with open(file,"rb") as f:
            data=f.read()

            encrpted_file=fernet.Fernet(self.key).encrypt(data)

            with open("%s_encrypted"%file,"wb") as f_:
                f_.write(encrpted_file)

        res=self.client.add("%s_encrypted"%file)
        #删除加密文件,防止积累
        os.remove("./%s_encrypted"%file)
        upload=[]#可能需要加密
        upload.append(res['Hash'])

        key=str(self.key,encoding="utf-8")

        upload.append(key)
        upload=" ".join(upload)#上链字符串数据
        print(upload)
        ciphertext,capsule=pre.encrypt(self.pub_key,bytes(upload,encoding="utf-8"))
        #print(ciphertext)
        #可能需要非对称加密
        upload_data=self.w3.toHex(ciphertext)
        txo = {}
        txo['from'] = self.w3.eth.accounts[0]
        txo['to'] = self.w3.eth.accounts[1]
        txo['value'] = self.w3.toHex(0)
        txo['data'] = upload_data
        self.w3.geth.personal.unlockAccount(self.w3.eth.accounts[0], "123456")
        transaction_hash = self.w3.eth.sendTransaction(txo)#交易hash可以以数据库形式存储
        self.w3.geth.miner.start()
        self.w3.eth.waitForTransactionReceipt(transaction_hash)
        self.w3.geth.miner.stop()
        print("成功上链")
        #建立交易哈希与capsule的键值关系,保存至json文件
        #self.record[transaction_hash]=capsule
        capsule=capsule.to_bytes()#capsule
        #print(type(capsule))
        #transaction_hash=transaction_hash.hex()
        data={transaction_hash:capsule}
        print(data)
        if not os.path.exists("data.pkl"):
            list=[]
            with open("data.pkl","wb") as f:
                list.append(data)
                pickle.dump(list,f)
        else:
            fr=open("data.pkl","rb")
            old_pickle=pickle.load(fr)
            fr.close()
            old_pickle.append(data)
            with open("data.pkl","wb") as f:
                pickle.dump(old_pickle,f)
        data={"IP":self.IP,"tx_hash":transaction_hash.hex()}
        responce=requests.post(url="http://10.134.205.182:8085/sendjson",json=data,verify=False)
        if responce.status_code==200:
            print("上传完毕")
Example #21
0
def get_signer_keys ():
    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)
    newkeys = {"privateSigningKey": alices_signing_key, "publicSigningKey": alices_verifying_key, "signer": alices_signer}
    # print (newkeys) 
    with open("python/proxy/23.jpg", "rb") as imageFile:
        f = imageFile.read()
        plaintext = bytes(f)
    # print("imgStart")
    # print(b)
    # print("imgEnd")

    # plaintext = b'Proxy Re-encryption is cool!'
    # print("@@@@")
    # print(plaintext)
    ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)
    # print(ciphertext)
    print(capsule)
    bob_capsule = capsule
    bobs_private_key = keys.UmbralPrivateKey.gen_key()
    bobs_public_key = bobs_private_key.get_pubkey()
    kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
                                signer=alices_signer,
                                receiving_pubkey=bobs_public_key,
                                threshold=10,
                                N=20)
    print(kfrags)
    bob_capsule.set_correctness_keys(delegating=alices_public_key,
                                 receiving=bobs_public_key,
                                 verifying=alices_verifying_key)
Example #22
0
    def file_encrypt_and_upload(self, file):

        symmetric_key = fernet.Fernet.generate_key()
        with open(file, "rb") as f:
            data = f.read()
            encrpted_file = fernet.Fernet(symmetric_key).encrypt(data)
            encrypted_key, capsule = pre.encrypt(self.pub_key, symmetric_key)
            print(encrypted_key)
            upload = encrpted_file + b"   " + encrypted_key
            res = self.client.add_bytes(upload)
            print(res, capsule)
            data_now = {res: capsule}
            self.record.update(data_now)
            capsule = capsule.to_bytes()

            data = {res: capsule}

            if not os.path.exists("data.pkl"):
                list = []
                with open("data.pkl", "wb") as f:
                    list.append(data)
                    pickle.dump(list, f)
                    print("file upload sucess")
            else:
                fr = open("data.pkl", "rb")
                old_pickle = pickle.load(fr)
                fr.close()
                old_pickle.append(data)
                with open("data.pkl", "wb") as f:
                    pickle.dump(old_pickle, f)
                    print("file upload success")
Example #23
0
def test_public_key_encryption(alices_keys):
    delegating_privkey, _ = alices_keys
    plain_data = b'peace at dawn'
    ciphertext, capsule = pre.encrypt(delegating_privkey.get_pubkey(),
                                      plain_data)
    cleartext = pre.decrypt(ciphertext, capsule, delegating_privkey)
    assert cleartext == plain_data
 def newKey(self, keyName, keyValue, path):
     keyValue, keyCapsule = pre.encrypt(self.publicKey, keyValue)
     keyCapsule = keyCapsule.to_bytes()
     tx = self._buildTx().newKey(keyName, keyValue, keyCapsule, self.publicKeyBytes)
     result = self._ethTransaction(tx)
     if result:
         print('Key added')
     else:
         print('Key is already exist')
 def updateKey(self, keyName, keyValue, path):
     keyValue, keyCapsule = pre.encrypt(self.publicKey, keyValue)
     keyCapsule = keyCapsule.to_bytes()
     tx = self._buildTx().updateKey(keyName, keyValue, keyCapsule)
     result = self._ethTransaction(tx)
     if result:
         print('Key updated')
     else:
         print('Key is not exist or you not creator')
Example #26
0
 def encrypto(self, clear_text, owner_public_key):
     crypto_start_time = time.time()
     ciphertext, capsule = pre.encrypt(owner_public_key, clear_text)
     print('{}   {}'.format(sys.getsizeof(ciphertext),
                            sys.getsizeof(capsule)))
     crypto_end_time = time.time()
     timeUsed = type_convert.double_process(crypto_end_time -
                                            crypto_start_time)
     return ciphertext, capsule, timeUsed
Example #27
0
def en(alices_public_key, plaintext):
    ################# ENCRYPT
    # Encrypt data with Alice's public key.
    ################# []
    # plaintext = b'Proxy Re-Encryption is cool!'

    ciphertext, capsule = pre.encrypt(alices_public_key, str.encode(plaintext))

    # print("params", params.to_bytes())
    return ciphertext, capsule
Example #28
0
def encrypt_():
    user_id = request.args.get('user_id')
    if not user_id in users:
        print("User not found, creating new")
        new_user(user_id)

    user = users[user_id]
    global capsule
    ciphertext, capsule = pre.encrypt(user['pubk'],
                                      request.args.get('msg').encode())
    return base64.b64encode(ciphertext).decode()
Example #29
0
def encrypt_message(receiver_pub_key, plaintext, sender_priv_key):

    ciphertext, capsule = pre.encrypt(receiver_pub_key, plaintext)

    kfrags = pre.split_rekey(sender_priv_key, receiver_pub_key, 10, 20)

    for k in kfrags:

        cfrag = pre.reencrypt(kfrag, capsule)
        capsule.attach_cfrag(cfrag)

    return ciphertext, capsule
Example #30
0
    def encrypt_for(
        self,
        recipient: "Character",
        plaintext: bytes,
        sign: bool = True,
        sign_plaintext=True,
    ) -> tuple:
        """
        Encrypts plaintext for recipient actor. Optionally signs the message as well.

        :param recipient: The character whose public key will be used to encrypt
            cleartext.
        :param plaintext: The secret to be encrypted.
        :param sign: Whether or not to sign the message.
        :param sign_plaintext: When signing, the cleartext is signed if this is
            True,  Otherwise, the resulting ciphertext is signed.

        :return: A tuple, (ciphertext, signature).  If sign==False,
            then signature will be NOT_SIGNED.
        """
        recipient_pubkey_enc = recipient.public_key(EncryptingPower)
        if sign:
            if sign_plaintext:
                # Sign first, encrypt second.
                signature = self.stamp(plaintext)
                ciphertext, capsule = pre.encrypt(recipient_pubkey_enc,
                                                  signature + plaintext)
            else:
                # Encrypt first, sign second.
                ciphertext, capsule = pre.encrypt(recipient_pubkey_enc,
                                                  plaintext)
                signature = self.stamp(ciphertext)
        else:
            # Don't sign.
            signature = NOT_SIGNED
            ciphertext, capsule = pre.encrypt(recipient_pubkey_enc, plaintext)

        message_kit = MessageKit(ciphertext=ciphertext, capsule=capsule)
        message_kit.alice_pubkey = self.public_key(SigningPower)
        return message_kit, signature