Created
April 28, 2024 08:41
-
-
Save 2tony2/a9ad9c3014703cf00579c0c5a71735a8 to your computer and use it in GitHub Desktop.
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
from abc import ABC, abstractmethod | |
from contextlib import contextmanager | |
from cryptography.fernet import Fernet | |
class CryptoFileManager(ABC): | |
@abstractmethod | |
@contextmanager | |
def secure_file_handler(self, path, mode, key): | |
"""A context manager for encrypting or decrypting files.""" | |
pass | |
class FileEncryptor(CryptoFileManager): | |
@contextmanager | |
def secure_file_handler(self, path, mode, key): | |
"""Encrypts file content on write.""" | |
try: | |
cipher = Fernet(key) | |
with open(path, mode) as file: | |
data = file.read() | |
encrypted_data = cipher.encrypt(data.encode()) | |
file.seek(0) | |
file.write(encrypted_data.decode()) | |
yield file | |
except Exception as e: | |
print(f"Failed to encrypt file: {e}") | |
finally: | |
print(f"File encryption completed and file {path} has been closed.") | |
class FileDecryptor(CryptoFileManager): | |
@contextmanager | |
def secure_file_handler(self, path, mode, key): | |
"""Decrypts file content on read.""" | |
file = None | |
try: | |
cipher = Fernet(key) | |
file = open(path, mode) | |
encrypted_data = file.read() | |
decrypted_data = cipher.decrypt(encrypted_data.encode()) | |
file.seek(0) | |
file.write(decrypted_data.decode()) | |
file.seek(0) | |
yield file | |
except Exception as e: | |
print(f"Failed to decrypt file: {e}") | |
finally: | |
if file: | |
file.close() | |
print(f"File decryption completed and file {path} has been closed.") | |
# Example usage | |
key = Fernet.generate_key() # Normally you would store and retrieve this securely | |
if __name__ == "__main__": | |
encryptor = FileEncryptor() | |
decryptor = FileDecryptor() | |
# Encrypt data | |
with encryptor.secure_file_handler('testfile.txt', 'w+', key) as file: | |
file.write("Sensitive data that needs encryption.") | |
# Decrypt data | |
with decryptor.secure_file_handler('testfile.txt', 'r+', key) as file: | |
print("Decrypted content:", file.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment