Initial commit: 000-platform project skeleton
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
37
backend/app/services/crypto.py
Normal file
37
backend/app/services/crypto.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""配置加密服务"""
|
||||
import base64
|
||||
from cryptography.fernet import Fernet
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||
|
||||
from ..config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _get_fernet() -> Fernet:
|
||||
"""获取Fernet实例"""
|
||||
# 使用PBKDF2从密钥派生32字节密钥
|
||||
kdf = PBKDF2HMAC(
|
||||
algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=b'platform_salt_2026',
|
||||
iterations=100000,
|
||||
)
|
||||
key = base64.urlsafe_b64encode(kdf.derive(settings.CONFIG_ENCRYPT_KEY.encode()))
|
||||
return Fernet(key)
|
||||
|
||||
|
||||
def encrypt_value(value: str) -> str:
|
||||
"""加密配置值"""
|
||||
f = _get_fernet()
|
||||
encrypted = f.encrypt(value.encode())
|
||||
return base64.urlsafe_b64encode(encrypted).decode()
|
||||
|
||||
|
||||
def decrypt_value(encrypted_value: str) -> str:
|
||||
"""解密配置值"""
|
||||
f = _get_fernet()
|
||||
encrypted = base64.urlsafe_b64decode(encrypted_value.encode())
|
||||
decrypted = f.decrypt(encrypted)
|
||||
return decrypted.decode()
|
||||
Reference in New Issue
Block a user