Sometimes, we want to encode a string according to a password with Python.
In this article, we’ll look at how to encode a string according to a password with Python.
How to encode a string according to a password with Python?
To encode a string according to a password with Python, we can use the cryptography library.
To install it, we run
pip install cryptography
Then we use it by writing
from cryptography.fernet import Fernet
key = Fernet.generate_key()
from cryptography.fernet import Fernet
def encrypt(message: bytes, key: bytes) -> bytes:
return Fernet(key).encrypt(message)
def decrypt(token: bytes, key: bytes) -> bytes:
return Fernet(key).decrypt(token)
message = 'John Doe'
token = encrypt(message.encode(), key)
decoded = decrypt(token, key).decode()
to create the encryption key with generate_key.
And then we call encrypt in the encrypt function to encrypt the message byte string with the key.
In the decrypt function, we call decrypt with the token byte string to decrypt the string with the key.
And then we call decode to decode the byte string into the original string.
Conclusion
To encode a string according to a password with Python, we can use the cryptography library.