-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.py
More file actions
36 lines (31 loc) · 1.25 KB
/
Copy pathencryption.py
File metadata and controls
36 lines (31 loc) · 1.25 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
34
35
36
import os
from cryptography.fernet import Fernet
from dotenv import load_dotenv, set_key
# Path to .env file in the same directory
ENV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
load_dotenv(ENV_PATH)
def _get_or_create_encryption_key() -> bytes:
key = os.environ.get("VAPI_ENCRYPTION_KEY")
if not key:
# Generate a new Fernet key
new_key = Fernet.generate_key().decode()
# Create .env file if it doesn't exist, and write the key
with open(ENV_PATH, "a") as f:
pass # Ensure file exists
set_key(ENV_PATH, "VAPI_ENCRYPTION_KEY", new_key)
# Set in current environment
os.environ["VAPI_ENCRYPTION_KEY"] = new_key
key = new_key
return key.encode()
# Initialize Fernet cipher suite
_fernet = Fernet(_get_or_create_encryption_key())
def encrypt_key(plain_text: str) -> str:
"""Encrypts a plain text string (e.g. API key) to a token string."""
if not plain_text:
return ""
return _fernet.encrypt(plain_text.encode()).decode()
def decrypt_key(encrypted_text: str) -> str:
"""Decrypts a token string back to the original plain text."""
if not encrypted_text:
return ""
return _fernet.decrypt(encrypted_text.encode()).decode()