crypto_1.py 752 B

12345678910111213141516171819202122232425
  1. def aes(key, data, counter=False):
  2. """ encrypt data with aes, using either pycryptopp or PyCrypto.
  3. Args
  4. key: The encryption key
  5. data: plain text data
  6. counter: a callable, usually not needed
  7. """
  8. # using either pycryptopp...
  9. if hasattr(AES, "process"):
  10. a = AES(key)
  11. return a.process(data)
  12. # ... or PyCrypto
  13. counter = counter or Counter()
  14. a = AES.new(key, AES.MODE_CTR, counter=counter)
  15. rest = len(data) % 16
  16. if not rest:
  17. return a.encrypt(data)
  18. # Data length must be a multiple of 16
  19. # Pad with bytes all of the same value as the number of padding bytes
  20. pad = (16 - rest)
  21. data += chr(pad) * pad
  22. return a.encrypt(data)[:-pad]