Last active
March 17, 2025 13:26
-
-
Save mostafabahri/a5cfdd69c78cde1d57e67265b01a6888 to your computer and use it in GitHub Desktop.
Fernet encryption example with password
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from cryptography.fernet import Fernet | |
from kdf import derive_key | |
passphrase = b"hunter2" | |
f = Fernet(derive_key(passphrase)) | |
with open('encrypted.txt', 'rb') as file: | |
encrypted = file.read() # binary read | |
plaintext = f.decrypt(encrypted) # binary output | |
print(plaintext.decode()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from cryptography.fernet import Fernet | |
from kdf import derive_key | |
passphrase = b"hunter2" | |
key = derive_key(passphrase, salt_gen=True) | |
f = Fernet(key) | |
with open('plain.txt', 'rb') as file: | |
plaintext = file.read() # binary read | |
plaintext += b"Hey new data!" | |
with open('encrypted.txt', 'wb') as file: | |
file.write(f.encrypt(plaintext)) # binary write |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC | |
from cryptography.hazmat.backends import default_backend | |
import os | |
import base64 | |
def derive_key(passphrase, generate_salt=False): | |
salt = SaltManager(generate_salt) | |
kdf = PBKDF2HMAC( | |
algorithm=hashes.SHA256(), | |
length=32, | |
salt=salt.get(), | |
iterations=1000, | |
backend=default_backend() | |
) | |
return base64.urlsafe_b64encode(kdf.derive(passphrase)) | |
class SaltManager(object): | |
def __init__(self, generate, path='.salt'): | |
self.generate = generate | |
self.path = path | |
def get(self): | |
if self.generate: | |
return self._generate_and_store() | |
return self._read() | |
def _generate_and_store(self): | |
salt = os.urandom(16) | |
with open(self.path, 'wb') as f: | |
f.write(salt) | |
return salt | |
def _read(self): | |
with open(self.path, 'rb') as f: | |
return f.read() |
thank you for your effort. made my life a little easier.
thx dude, you helped so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for sharing your code much appreciated