Skip to content

Instantly share code, notes, and snippets.

@mostafabahri
Last active May 2, 2024 00:37
Show Gist options
  • Save mostafabahri/a5cfdd69c78cde1d57e67265b01a6888 to your computer and use it in GitHub Desktop.
Save mostafabahri/a5cfdd69c78cde1d57e67265b01a6888 to your computer and use it in GitHub Desktop.
Fernet encryption example with password
#!/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())
#!/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
#!/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()
@Anas-jaf
Copy link

thanks for sharing your code much appreciated

@GuruOz
Copy link

GuruOz commented Feb 9, 2024

thank you for your effort. made my life a little easier.

@cebem1nt
Copy link

thx dude, you helped so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment