Created
February 25, 2025 21:23
-
-
Save ryanlong1004/7824733b1572d7b8e2ce194f5521eed0 to your computer and use it in GitHub Desktop.
Python string encryption/decryption
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
from cryptography.fernet import Fernet | |
class Crypt: | |
def __init__(self, key: str): | |
self.key = key.encode() | |
self.cipher = Fernet(self.key) | |
def encrypt(self, plaintext: str) -> str: | |
encrypted_text = self.cipher.encrypt(plaintext.encode()) | |
return encrypted_text.decode() | |
def decrypt(self, encrypted_text: str) -> str: | |
decrypted_text = self.cipher.decrypt(encrypted_text.encode()) | |
return decrypted_text.decode() | |
# Example usage: | |
# key = Fernet.generate_key().decode() # Generate a new key | |
# crypt = Crypt(key) | |
# encrypted = crypt.encrypt("Hello, World!") | |
# decrypted = crypt.decrypt(encrypted) | |
# print(f"Encrypted: {encrypted}") | |
# print(f"Decrypted: {decrypted}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment