Python Forum
Encrypt and decrypt in python using own fixed key - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Encrypt and decrypt in python using own fixed key (/thread-36432.html)



Encrypt and decrypt in python using own fixed key - SriRajesh - Feb-19-2022

Hi I want to encrypt an d decrypt. But I want to use fixed defined key for example: key = "Abcd123". Can some one help how to do it. Thanks in advance. I use below code.
from cryptography.fernet import Fernet
message = "I am python" 
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
print("original string: ", message)
print("encrypted string: ", encMessage)
decMessage = fernet.decrypt(encMessage).decode()
 
print("decrypted string: ", decMessage)



RE: Encrypt and decrypt in python using own fixed key - dboxall123 - Feb-19-2022

Hi. I can't say that I've ever used the cryptography module, but I got this and modified this from the cryptography website:
import base64
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
salt = os.urandom(16)
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=390000,
)
message = b"I am python"
password = b"Abcd123"
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)
encMessage = f.encrypt(message)
print(encMessage)
decMessage = f.decrypt(encMessage)
print(decMessage.decode('utf-8'))



RE: Encrypt and decrypt in python using own fixed key - SriRajesh - Feb-20-2022

(Feb-19-2022, 01:03 PM)dboxall123 Wrote: Hi. I can't say that I've ever used the cryptography module, but I got this and modified this from the cryptography website:
import base64
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
salt = os.urandom(16)
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=390000,
)
message = b"I am python"
password = b"Abcd123"
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)
encMessage = f.encrypt(message)
print(encMessage)
decMessage = f.decrypt(encMessage)
print(decMessage.decode('utf-8'))

It show error:
TypeError:__init__() missing 1 positional argument:'backend'


RE: Encrypt and decrypt in python using own fixed key - dboxall123 - Feb-20-2022

It's working perfectly here. Post the complete error.