crypto.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python
  2. # License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
  3. import os
  4. from . import BaseTest
  5. def is_rlimit_memlock_too_low() -> bool:
  6. ''' On supported systems, return true if the MEMLOCK limit is too low to
  7. run the crypto test. '''
  8. try:
  9. import resource
  10. except ModuleNotFoundError:
  11. return False
  12. memlock_limit, _ = resource.getrlimit(resource.RLIMIT_MEMLOCK)
  13. pagesize = resource.getpagesize()
  14. return memlock_limit <= pagesize
  15. class TestCrypto(BaseTest):
  16. def test_elliptic_curve_data_exchange(self):
  17. if is_rlimit_memlock_too_low():
  18. self.skipTest('RLIMIT_MEMLOCK is too low')
  19. from kitty.fast_data_types import AES256GCMDecrypt, AES256GCMEncrypt, CryptoError, EllipticCurveKey
  20. alice = EllipticCurveKey()
  21. bob = EllipticCurveKey()
  22. alice_secret = alice.derive_secret(bob.public)
  23. bob_secret = bob.derive_secret(alice.public)
  24. self.assertEqual(len(alice_secret), 32)
  25. self.assertEqual(len(bob_secret), 32)
  26. self.assertEqual(alice_secret, bob_secret)
  27. auth_data = os.urandom(213)
  28. plaintext = os.urandom(1011)
  29. e = AES256GCMEncrypt(alice_secret)
  30. e.add_authenticated_but_unencrypted_data(auth_data)
  31. ciphertext = e.add_data_to_be_encrypted(plaintext, True)
  32. d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
  33. d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
  34. q = d.add_data_to_be_decrypted(ciphertext, True)
  35. self.ae(q, plaintext)
  36. def corrupt_data(data):
  37. b = bytearray(data)
  38. b[0] = (b[0] + 13) % 256
  39. return bytes(b)
  40. d = AES256GCMDecrypt(bob_secret, e.iv, corrupt_data(e.tag))
  41. d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
  42. self.assertRaises(CryptoError, d.add_data_to_be_decrypted, ciphertext, True)
  43. d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
  44. d.add_data_to_be_authenticated_but_not_decrypted(corrupt_data(auth_data))
  45. self.assertRaises(CryptoError, d.add_data_to_be_decrypted, ciphertext, True)
  46. d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
  47. d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
  48. self.assertRaises(CryptoError, d.add_data_to_be_decrypted, corrupt_data(ciphertext), True)