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_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
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)
def test_decryption_error(alices_keys, bobs_keys, ciphertext_and_capsule, message): delegating_privkey, _signing_privkey = alices_keys receiving_privkey, _receiving_pubkey = bobs_keys ciphertext, capsule = ciphertext_and_capsule cleartext = pre.decrypt(ciphertext, capsule, delegating_privkey) assert message == cleartext with pytest.raises(pre.UmbralDecryptionError) as e: _cleartext = pre.decrypt(ciphertext, capsule, receiving_privkey)
def run_test(): alices_private_key_bytes = keys.UmbralPrivateKey.gen_key().to_bytes() alices_private_key = keys.UmbralPrivateKey.from_bytes( alices_private_key_bytes) alices_public_key = alices_private_key.get_pubkey() # print("Alices private key:", alices_private_key.to_bytes()) # print("Alices public key:", alices_public_key.to_bytes()) alices_signing_key = keys.UmbralPrivateKey.gen_key() alices_verifying_key = alices_signing_key.get_pubkey() alices_signer = signing.Signer(private_key=alices_signing_key) 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) cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=alices_private_key) # Requires: kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key, signer=alices_signer, receiving_pubkey=bobs_public_key, threshold=10, N=20) capsule.set_correctness_keys(delegating=alices_public_key, receiving=bobs_public_key, verifying=alices_verifying_key) cfrags = list() for kfrag in kfrags[:10]: cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule) cfrags.append(cfrag) for cfrag in cfrags: capsule.attach_cfrag(cfrag) bob_cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=bobs_private_key) print("Plain text: ", plaintext) print("bob_cleartext: ", bob_cleartext) assert bob_cleartext == plaintext
def decrypt(): # Get data from request json_data = json.loads(request.data.decode('utf-8')) ciphertext, policy_id, capsule, alice_pubkey, alice_signing_pubkey = json_data[ 'ciphertext'], json_data['policy_id'], json_data['capsule'], json_data[ 'alice_pubkey'], json_data['alice_signing_pubkey'] # convert to bytes ciphertext = string_to_bytes(ciphertext) capsule = string_to_bytes(capsule) capsule = pre.Capsule.from_bytes(capsule, params.UmbralParameters(SECP256K1)) alice_pubkey = string_to_bytes(alice_pubkey) alice_pubkey = keys.UmbralPublicKey.from_bytes(alice_pubkey) alice_signing_pubkey = string_to_bytes(alice_signing_pubkey) alice_signing_pubkey = keys.UmbralPublicKey.from_bytes( alice_signing_pubkey) # Perform re-encryption request bob_cfrags = mock_kms.reencrypt(policy_id, capsule, 10) # Simulate capsule handoff, and set the correctness keys. # Correctness keys are used to prove that a cfrag is correct and not modified # by a proxy node in the network. They must be set to use the `decrypt` and # `attach_cfrag` funtions. bob_capsule = capsule bob_capsule.set_correctness_keys(alice_pubkey, bob_pubkey, alice_signing_pubkey) for cfrag in bob_cfrags: bob_capsule.attach_cfrag(cfrag) decrypted_data = pre.decrypt(ciphertext, bob_capsule, bob_privkey, alice_signing_pubkey) return jsonify({ "decrypted_data": decrypted_data.decode('utf-8'), })
def post(self, request, *args, **kwargs): # import pdb;pdb.set_trace() data = QueryDict(request.body) try: capsule = mapper.get(data.get('capsule')) ciphertext = mapper.get(data.get('ciphertext')) print('CIPHERTEXT: ' + str(ciphertext)) print(alices_private_key) print('CAPSULE:' + str(capsule.to_bytes())) cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=alices_private_key) print(cleartext) tem = str(cleartext).split("'")[1] test_file = open('geek.txt', 'w+') test_file.write(tem) response = HttpResponse(content=test_file, content_type='application/pdf') # response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'attachment; filename="%s.txt"' \ % 'decrypted' return response except Exception: return HttpResponse( 'Your capsule or ciphertext is incorrect...Please check', status=400)
def decrypt(account, a_pub_key_bytes, a_ver_key_bytes, ciphertext, cfrags_bytes, capsule_bytes) -> str: with open(account + '_privacy', 'rb') as f: user_info_bytes = pickle.load(f) f.close() pri_key = keys.UmbralPrivateKey.from_bytes(user_info_bytes['private_key']) pub_key = pri_key.get_pubkey() a_pub_key = keys.UmbralPublicKey.from_bytes(a_pub_key_bytes) a_ver_key = keys.UmbralPublicKey.from_bytes(a_ver_key_bytes) capsule = pre.Capsule.from_bytes(capsule_bytes, pub_key.params) capsule.set_correctness_keys(delegating=a_pub_key, receiving=pub_key, verifying=a_ver_key) cfrags = list() for cfrag_bytes in cfrags_bytes: cfrag = pre.CapsuleFrag.from_bytes(cfrag_bytes) cfrags.append(cfrag) for cfrag in cfrags: capsule.attach_cfrag(cfrag) img_bytes = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=pri_key) img = base64.b64decode(img_bytes) with open('return_example.jpeg', 'wb') as f: f.write(img) f.close() path = os.path.abspath(__file__) + '/return_example.jpeg' return path
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)
def decrypt_file(self, alice_ciphertext, umbral_capsule, output_path): # Decrypt data for Alice with open(output_path, 'wb') as decoded_file: alice_decrypted_data = pre.decrypt(alice_ciphertext, umbral_capsule, self.priv_key, self.pub_key) decoded_file.write(alice_decrypted_data)
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)
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}' } )
def _decrypt(self, ciphertext, capsule): value = pre.decrypt( ciphertext = ciphertext, capsule = capsule, decrypting_key = self.privateKey ).decode('utf-8') return value
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
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 decrypt(): if request.content_type.lower() != "application/json": abort(415) data = request.get_json() if "receiverPrivateKey" in data and "ciphertext" in data and "capsule" in data: try: start = time.perf_counter() privateKey = keys.UmbralPrivateKey.from_bytes( bytes.fromhex(data["receiverPrivateKey"])) ciphertext = bytes.fromhex(data["ciphertext"]) capsule = pre.Capsule.from_bytes(bytes.fromhex(data["capsule"]), config.default_params()) plaintext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=privateKey) end = time.perf_counter() time_stats_endpoints["decrypt"].append(end - start) return {"status": "ok", "plaintext": plaintext.decode("utf-8")} except Exception as e: return {"status": "error", "error": str(e)} abort(400)
def decrypt(self, ciphertext): try: fail_decrypted_data = pre.decrypt( ciphertext=ciphertext, capsule=self.capsule, decrypting_key=self.bobs_private_key) except pre.UmbralDecryptionError: print("Decryption failed! Bob doesn't has access granted yet.")
def checkMessage(self, ciphertext, capsule): cleartext = pre.decrypt( ciphertext=ciphertext, capsule=capsule, decrypting_key=self.keys.get_recrpto_private_Key()) if (cleartext == self.message): return True else: return False
def decrypt(): if request.method == 'POST': # Get the private key bobPrivKey = string_to_bytes(request.form["bobPrivKey"]) bobPrivKey = keys.UmbralPrivateKey.from_bytes(bobPrivKey) bobPubKey = bobPrivKey.get_pubkey() # read the capsule from the json dump with open('data.json') as json_file: data1 = json.load(json_file) ciphertext = string_to_bytes(data1['ciphertext']) capsule = string_to_bytes(data1['capsule']) capsule = pre.Capsule.from_bytes( capsule, params.UmbralParameters(SECP256K1)) # get the kfrags with open('hospital.json') as json_file: data2 = json.load(json_file) # kfrags = data2['kfrags'] alicePubKey = string_to_bytes(data2["alicePubKey"]) alicePubKey = keys.UmbralPublicKey.from_bytes(alicePubKey) alice_verifying_key = string_to_bytes(data2["alice_verifying_key"]) alice_verifying_key = keys.UmbralPublicKey.from_bytes( alice_verifying_key) global kfrags kfrags = random.sample(kfrags, 10) capsule.set_correctness_keys(delegating=alicePubKey, receiving=bobPubKey, verifying=alice_verifying_key) cfrags = list() for kfrag in kfrags: cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule) cfrags.append(cfrag) capsule.set_correctness_keys(delegating=alicePubKey, receiving=bobPubKey, verifying=alice_verifying_key) for cfrag in cfrags: capsule.attach_cfrag(cfrag) #decrypt the data plainBobtext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=bobPrivKey) plainBobtext = plainBobtext.decode('utf-8') return render_template('decrypt.html', plainBobtext=plainBobtext, data=data1) with open('data.json') as json_file: data1 = json.load(json_file) return render_template('decrypt.html', data=data1)
def decrypt_reencrypted(ciphertext, private_key): for cfrag in cfrags: capsule.attach_cfrag(cfrag) bob_cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=private_key) return bob_cleartext
def decrypt_ciphertext(priv_key_str_hex, capsule_hex, ciphertext_hex): priv_key = keys.UmbralPrivateKey.from_bytes( bytes.fromhex(priv_key_str_hex)) params = UmbralParameters(curve=curve) ciphertext = bytes.fromhex(ciphertext_hex) capsule = pre.Capsule.from_bytes(bytes.fromhex(capsule_hex), params) cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=priv_key) return cleartext.decode("utf-8")
def decrypt_and_return(fileName, private_key, public_key): # Decrypt data with Alice's private key. try: with open(fileName, 'rb') as f: ciphertext = f.read() cleartext = pre.decrypt(capsule, private_key, ciphertext, alices_public_key) return cleartext, None except Exception as e: return None, e
def decrypt_file(uid, filename, capsule): print("decryption in progress") with open(f"{ASSYMETRIC_KEY_PATH}/{uid}_private_key.pem", "rb") as key_file: private_key = key_file.read() private_key = keys.UmbralPrivateKey.from_bytes(private_key) with open(f"{ENCRYPTED_FILES_PATH}/{filename}_encrypted", 'rb') as file: cipherdata = file.read() original_data = pre.decrypt(ciphertext=cipherdata, capsule=capsule, decrypting_key=private_key)
def decrypt(self, message_kit: MessageKit) -> bytes: """ Decrypt data encrypted with Umbral. :param message_kit: A KMS MessageKit. :return: bytes """ cleartext = pre.decrypt(message_kit.capsule, self._privkey, message_kit.ciphertext, message_kit.alice_pubkey) return cleartext
def getUser(self, userAddress): userAddress = Web3.toChecksumAddress(userAddress) user = self.ehr.getUser(userAddress) curveVar = curve.Curve(714) paramsVar = params.UmbralParameters(curveVar) firstNameCapsule = pre.Capsule.from_bytes(user[0], paramsVar) lastNameCapsule = pre.Capsule.from_bytes(user[1], paramsVar) dateOfBirthCapsule = pre.Capsule.from_bytes(user[2], paramsVar) firstName = pre.decrypt(ciphertext=user[3], capsule=firstNameCapsule, decrypting_key=self.privateKey) lastName = pre.decrypt(ciphertext=user[4], capsule=lastNameCapsule, decrypting_key=self.privateKey) dateOfBirth = pre.decrypt(ciphertext=user[5], capsule=dateOfBirthCapsule, decrypting_key=self.privateKey) firstName = firstName.decode('utf-8') lastName = lastName.decode('utf-8') dateOfBirth = dateOfBirth.decode('utf-8') return firstName, lastName, dateOfBirth
def decrypt(self, message_kit: MessageKit) -> bytes: """ Decrypt data encrypted with Umbral. :return: bytes """ cleartext = pre.decrypt(ciphertext=message_kit.ciphertext, capsule=message_kit.capsule, decrypting_key=self._privkey, ) return cleartext
def decrypt_and_return(filename, private_key, public_key): # Use the encrypted file and capsule to decrypt. try: with open(filename, 'rb') as f: capsule_file = "capsule_" + filename with open(capsule_file, 'rb') as f2: capsule = f2.read().fromBytes() ciphertext = f.read() cleartext = pre.decrypt(capsule, private_key, ciphertext, public_key) print(cleartext) except Exception as e: print(e)
def getAllDiseases(self, userAddress): userAddress = Web3.toChecksumAddress(userAddress) diseasesTimestamps = self.getDiseasesTimestamps(userAddress) curveVar = curve.Curve(714) paramsVar = params.UmbralParameters(curveVar) diseases = [] for diseaseTimestamp in diseasesTimestamps: disease = self.ehr.getDisease(userAddress, diseaseTimestamp) diagnosisCapsule = pre.Capsule.from_bytes(disease[3], paramsVar) therapyCapsule = pre.Capsule.from_bytes(disease[4], paramsVar) diagnosis = pre.decrypt(ciphertext=disease[5], capsule=diagnosisCapsule, decrypting_key=self.privateKey) therapy = pre.decrypt(ciphertext=disease[6], capsule=therapyCapsule, decrypting_key=self.privateKey) diseaseEncrypted = { 'diagnosis': diagnosis.decode('utf-8'), 'therapy': therapy.decode('utf-8') } diseases.append(diseaseEncrypted) return diseases
def get(self, request, *args, **kwargs): data = request.GET # import pdb;pdb.set_trace() ciphertext = data.get('ciphertext') print(ciphertext) # ciphertext = data.get('file_hash') cleartext = pre.decrypt(ciphertext=ciphertext, capsule=capsule, decrypting_key=alices_private_key) print(cleartext) self.output_response['res_data'] = tem return HttpResponse(json.dumps(self.output_response['res_data']), status=201)
def _decrypt_ciphertext( self, ciphertext: Dict[str, Tuple[bytes, Capsule]] ) -> Tuple[Tuple[UmbralPublicKey, Signer], UmbralPrivateKey]: """decrypt ciphertext Arguments: ciphertext {Dict[str, Tuple[bytes, Capsule]]} Returns: Tuple[Tuple[UmbralPublicKey, Signer], UmbralPrivateKey] -- (credential, private key) """ (enc_credential, c_capsule) = ciphertext["credential"] (enc_private_key, p_capsule) = ciphertext["private_key"] credential = decrypt(ciphertext=enc_credential, capsule=c_capsule, decrypting_key=self.private_key) private_key = decrypt(ciphertext=enc_private_key, capsule=p_capsule, decrypting_key=self.private_key) return (credential, private_key)