crypto.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from binascii import hexlify
  2. from attic.testsuite import AtticTestCase
  3. from attic.crypto import AES, bytes_to_long, bytes_to_int, long_to_bytes, pbkdf2_sha256, get_random_bytes
  4. class CryptoTestCase(AtticTestCase):
  5. def test_bytes_to_int(self):
  6. self.assert_equal(bytes_to_int(b'\0\0\0\1'), 1)
  7. def test_bytes_to_long(self):
  8. self.assert_equal(bytes_to_long(b'\0\0\0\0\0\0\0\1'), 1)
  9. self.assert_equal(long_to_bytes(1), b'\0\0\0\0\0\0\0\1')
  10. def test_pbkdf2_sha256(self):
  11. self.assert_equal(hexlify(pbkdf2_sha256(b'password', b'salt', 1, 32)),
  12. b'120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b')
  13. self.assert_equal(hexlify(pbkdf2_sha256(b'password', b'salt', 2, 32)),
  14. b'ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43')
  15. self.assert_equal(hexlify(pbkdf2_sha256(b'password', b'salt', 4096, 32)),
  16. b'c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a')
  17. def test_get_random_bytes(self):
  18. bytes = get_random_bytes(10)
  19. bytes2 = get_random_bytes(10)
  20. self.assert_equal(len(bytes), 10)
  21. self.assert_equal(len(bytes2), 10)
  22. self.assert_not_equal(bytes, bytes2)
  23. def test_aes(self):
  24. key = b'X' * 32
  25. data = b'foo' * 10
  26. aes = AES(key)
  27. self.assert_equal(bytes_to_long(aes.iv.raw, 8), 0)
  28. cdata = aes.encrypt(data)
  29. self.assert_equal(hexlify(cdata), b'c6efb702de12498f34a2c2bbc8149e759996d08bf6dc5c610aefc0c3a466')
  30. self.assert_equal(bytes_to_long(aes.iv.raw, 8), 2)
  31. self.assert_not_equal(data, aes.decrypt(cdata))
  32. aes.reset(iv=b'\0' * 16)
  33. self.assert_equal(data, aes.decrypt(cdata))