Created
July 9, 2023 06:38
-
-
Save ZeccaLehn/4e7e3331e4a44817bc5b43686c3c8909 to your computer and use it in GitHub Desktop.
Round Trip Encryption w/Python
This file contains 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
pip install cryptography | |
----------------- | |
from cryptography.fernet import Fernet | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC | |
import base64 | |
import os | |
# Generate a key using a password and a random salt | |
password = b"password" | |
salt = os.urandom(16) | |
kdf = PBKDF2HMAC( | |
algorithm=hashes.SHA256(), | |
length=32, | |
salt=salt, | |
iterations=100000, | |
) | |
key = base64.urlsafe_b64encode(kdf.derive(password)) | |
# Create a Fernet instance using the generated key | |
cipher_suite = Fernet(key) | |
# Read the contents of the file you want to encrypt | |
with open("input_file.txt", "rb") as file: | |
file_data = file.read() | |
# Encrypt the file data | |
encrypted_data = cipher_suite.encrypt(file_data) | |
# Write the encrypted data to a new file | |
with open("encrypted_file.txt", "wb") as file: | |
file.write(encrypted_data) | |
-------------------- | |
from cryptography.fernet import Fernet | |
import base64 | |
# Read the contents of the encrypted file | |
with open("encrypted_file.txt", "rb") as file: | |
encrypted_data = file.read() | |
# Generate the key using the same password and salt that was used to encrypt the file | |
password = b"password" | |
salt = os.urandom(16) | |
kdf = PBKDF2HMAC( | |
algorithm=hashes.SHA256(), | |
length=32, | |
salt=salt, | |
iterations=100000, | |
) | |
key = base64.urlsafe_b64encode(kdf.derive(password)) | |
# Create a Fernet instance using the generated key | |
cipher_suite = Fernet(key) | |
# Decrypt the encrypted data | |
decrypted_data = cipher_suite.decrypt(encrypted_data) | |
# Write the decrypted data to a new file | |
with open("decrypted_file.txt", "wb") as file: | |
file.write(decrypted_data) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment