test_api_crypto.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import unittest
  2. from app.core import api_crypto
  3. class ApiCryptoTests(unittest.TestCase):
  4. def test_derive_key_is_stable_for_same_input(self):
  5. key1 = api_crypto.derive_key(
  6. fixed_secret="fixed-secret",
  7. user_id="u1",
  8. ts=1714300000000,
  9. nonce="nonce-1",
  10. )
  11. key2 = api_crypto.derive_key(
  12. fixed_secret="fixed-secret",
  13. user_id="u1",
  14. ts=1714300000000,
  15. nonce="nonce-1",
  16. )
  17. self.assertEqual(key1, key2)
  18. self.assertEqual(len(key1), 32)
  19. def test_encrypt_decrypt_roundtrip(self):
  20. key = api_crypto.derive_key(
  21. fixed_secret="fixed-secret",
  22. user_id="u1",
  23. ts=1714300000000,
  24. nonce="nonce-1",
  25. )
  26. payload = {"a": 1, "b": "x"}
  27. cipher = api_crypto.encrypt_json(payload, key)
  28. plain = api_crypto.decrypt_json(cipher, key)
  29. self.assertEqual(plain, payload)
  30. def test_encrypt_decrypt_roundtrip_cbc(self):
  31. key = api_crypto.derive_key(
  32. fixed_secret="fixed-secret",
  33. user_id="u1",
  34. ts=1714300000000,
  35. nonce="nonce-2",
  36. )
  37. payload = {"list": [1, 2, 3], "ok": True}
  38. cipher = api_crypto.encrypt_json(payload, key, alg="cbc")
  39. plain = api_crypto.decrypt_json(cipher, key, alg="cbc")
  40. self.assertEqual(plain, payload)
  41. if __name__ == "__main__":
  42. unittest.main()