0

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 Answer 1

0

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!!'
1
  • 1
    Thanks a lot! It worked! First, it didnt though because i used the same key as in the first program i created, the program didnt like that. As soon as i gave the key a new name, and therefore a new key, it worked perfectly! Commented Oct 8, 2021 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.