encrypter.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import base64
  2. from extensions.ext_database import db
  3. from libs import rsa
  4. def obfuscated_token(token: str):
  5. if not token:
  6. return token
  7. if len(token) <= 8:
  8. return '*' * 20
  9. return token[:6] + '*' * 12 + token[-2:]
  10. def encrypt_token(tenant_id: str, token: str):
  11. from models.account import Tenant
  12. if not (tenant := db.session.query(Tenant).filter(Tenant.id == tenant_id).first()):
  13. raise ValueError(f'Tenant with id {tenant_id} not found')
  14. encrypted_token = rsa.encrypt(token, tenant.encrypt_public_key)
  15. return base64.b64encode(encrypted_token).decode()
  16. def decrypt_token(tenant_id: str, token: str):
  17. return rsa.decrypt(base64.b64decode(token), tenant_id)
  18. def batch_decrypt_token(tenant_id: str, tokens: list[str]):
  19. rsa_key, cipher_rsa = rsa.get_decrypt_decoding(tenant_id)
  20. return [rsa.decrypt_token_with_decoding(base64.b64decode(token), rsa_key, cipher_rsa) for token in tokens]
  21. def get_decrypt_decoding(tenant_id: str):
  22. return rsa.get_decrypt_decoding(tenant_id)
  23. def decrypt_token_with_decoding(token: str, rsa_key, cipher_rsa):
  24. return rsa.decrypt_token_with_decoding(base64.b64decode(token), rsa_key, cipher_rsa)