-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.py
More file actions
33 lines (24 loc) · 1.14 KB
/
Copy pathencryption.py
File metadata and controls
33 lines (24 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""Fernet symmetric encryption for storing API keys at rest."""
import os
import sys
from cryptography.fernet import Fernet
# ENCRYPTION_KEY must be a valid Fernet key (base64-encoded 32-byte key).
# Generate one with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
_key = os.getenv("ENCRYPTION_KEY")
ENCRYPTION_KEY_IS_EPHEMERAL = not _key
if not _key:
_key = Fernet.generate_key().decode()
print(
"\n *** WARNING: ENCRYPTION_KEY is not set! ***\n"
" Using a randomly generated key. Encrypted API keys will be\n"
" LOST when the app restarts. Set this env var for production:\n"
f" ENCRYPTION_KEY={_key}\n",
file=sys.stderr,
)
_fernet = Fernet(_key.encode() if isinstance(_key, str) else _key)
def encrypt(plaintext: str) -> str:
"""Encrypt a plaintext string and return the ciphertext as a UTF-8 string."""
return _fernet.encrypt(plaintext.encode("utf-8")).decode("utf-8")
def decrypt(ciphertext: str) -> str:
"""Decrypt a ciphertext string back to the original plaintext."""
return _fernet.decrypt(ciphertext.encode("utf-8")).decode("utf-8")