0
votes

I wanted to create a program where i could make some encryption, then send it to a friend, and then send him the encryption key and the decryption code and then he could decrypt the message himself. I have only figured out how to decrypt something based on the encryption, this is my attempt:

import cryptography

from cryptography.fernet import Fernet

key = Fernet.generate_key()

print(key)

with open("pass.key", "wb") as key_file: key_file.write(key)

def call_key():

              return open("pass.key", "rb").read()

key = call_key()

code = "Hello!! Awesome code!!".encode()

a = Fernet(key)

code = a.encrypt(code)

print(code)

key = call_key()

b = Fernet(key)

decoded_code = b.decrypt(code)

print(decoded_code)

The problem is for this to work the encrypted part has to be known. i want it so that it can be decrypted without knowing the original message. Thanks for your help:)

1

1 Answers

0
votes

I think you actually have both things you want, you just didn't split them apart yet. Let's say that you have two scripts instead of just the block of code you have.

encrypt.py:

from cryptography.fernet import Fernet

key = Fernet.generate_key()
print(key)
with open("pass.key", "wb") as key_file: key_file.write(key)
code = "Hello!! Awesome code!!".encode()
a = Fernet(key)
code = a.encrypt(code)
print(code)

Which produces some output where the first line is the key and the second line is the encoded message with the key you generated.

b'uRcjLwzI3N732Zy02kz35SfFJXgXY3EVKHmSo66xqUg='
b'gAAAAABhXztbKmk_2ALnJSawKjelg2wmn-hdq5dtpIJK0KbveL1pioAJRdNOzuh91acsA0ZFil5VOrSF8oAT4VoV_opezc8BTQMjsV3wkvq78OSEG850pGA='

Then let's say that you pass the byte string to your friend along with the key file pass.key. Then you can have, where s is the encoded message, decrypt.py:

from cryptography.fernet import Fernet

s = "gAAAAABhXztbKmk_2ALnJSawKjelg2wmn-hdq5dtpIJK0KbveL1pioAJRdNOzuh91acsA0ZFil5VOrSF8oAT4VoV_opezc8BTQMjsV3wkvq78OSEG850pGA="

code = bytes(s, "utf-8")
def call_key(): return open("pass.key", "rb").read()
key = call_key()
b = Fernet(key)
decoded_code = b.decrypt(code)
print(decoded_code)

which produces

b'Hello!! Awesome code!!'