0

I have this sample code that generates the key (password) by the fernet function to encrypt the string but what I want to do is choosing the password myself. How can I do it, please?

from cryptography.fernet import Fernet
key = Fernet.generate_key()
print(key)
message = "Hello World".encode()
key_obj = Fernet(key)
encrypted_message = key_obj.encrypt(message)
print(encrypted_message)
decrypted_message = key_obj.decrypt(encrypted_message)
print(decrypted_message)
Michael Fehr
  • 5,827
  • 2
  • 19
  • 40
Hakim2000
  • 21
  • 5
  • From the documentation [using passwords with Fernet](https://cryptography.io/en/latest/fernet.html#using-passwords-with-fernet). Alternatively possible answers [here](https://stackoverflow.com/questions/44432945/generating-own-key-with-python-fernet/44527133), or [here](https://incolumitas.com/2014/10/19/using-the-python-cryptography-module-with-custom-passwords/). – Thymen Mar 29 '21 at 14:59

1 Answers1

1

Fernet uses the key with "32 url-safe base64-encoded". If you want to set your own password, it should be of 32 bytes, e.g:

from cryptography.fernet import Fernet
import base64
key = base64.urlsafe_b64encode(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
print(key)
message = "Hello World".encode()
key_obj = Fernet(key)
encrypted_message = key_obj.encrypt(message)
print(encrypted_message)
decrypted_message = key_obj.decrypt(encrypted_message)
print(decrypted_message)
sinkmanu
  • 1,034
  • 1
  • 12
  • 24