41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
"""Utility functions"""
|
|
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
from app.config import settings
|
|
import base64
|
|
|
|
|
|
def get_cipher():
|
|
"""Get Fernet cipher for encryption"""
|
|
# Use first 32 bytes of encryption key, base64 encoded
|
|
key = settings.encryption_key.encode()[:32]
|
|
# Pad to 32 bytes if needed
|
|
key = key.ljust(32, b'0')
|
|
# Base64 encode for Fernet
|
|
key_b64 = base64.urlsafe_b64encode(key)
|
|
return Fernet(key_b64)
|
|
|
|
|
|
def encrypt_token(token: str) -> str:
|
|
"""Encrypt API token"""
|
|
cipher = get_cipher()
|
|
return cipher.encrypt(token.encode()).decode()
|
|
|
|
|
|
def decrypt_token(encrypted_token: str) -> str:
|
|
"""Decrypt API token
|
|
|
|
Raises:
|
|
ValueError: If token cannot be decrypted (wrong encryption key)
|
|
"""
|
|
cipher = get_cipher()
|
|
try:
|
|
return cipher.decrypt(encrypted_token.encode()).decode()
|
|
except InvalidToken:
|
|
raise ValueError(
|
|
"Не удалось расшифровать API токен. "
|
|
"Возможно, ключ шифрования (ENCRYPTION_KEY) был изменен. "
|
|
"Пожалуйста, обновите API токен для этого репозитория."
|
|
)
|
|
|