28 lines
863 B
Python
28 lines
863 B
Python
import os
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
|
|
def get_fernet():
|
|
key = os.environ.get("ENCRYPTION_KEY")
|
|
if not key:
|
|
# Fallback to an ephemeral key if missing to prevent crashing,
|
|
# though data encrypted with this will be lost on restart
|
|
key = Fernet.generate_key()
|
|
os.environ["ENCRYPTION_KEY"] = key.decode('utf-8')
|
|
return Fernet(key)
|
|
|
|
def encrypt_password(password: str) -> str:
|
|
if not password:
|
|
return password
|
|
f = get_fernet()
|
|
return f.encrypt(password.encode('utf-8')).decode('utf-8')
|
|
|
|
def decrypt_password(token: str) -> str:
|
|
if not token:
|
|
return token
|
|
f = get_fernet()
|
|
try:
|
|
return f.decrypt(token.encode('utf-8')).decode('utf-8')
|
|
except InvalidToken:
|
|
# If decryption fails, assume it's a legacy plaintext password
|
|
return token
|