crypt.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from Crypto.Cipher import AES
  2. from random import randint
  3. key = "aaaabbbbccccdddd"
  4. def decr(ciphertext):
  5. iv = ciphertext[:16]
  6. c = ciphertext[17:]
  7. cipher = AES.new(key, AES.MODE_CBC, iv)
  8. return ispkcs7(cipher.decrypt(c))
  9. """ decrypts the ct and returns it when padding is ok, else retuirn False """
  10. def decrypt(ciphertext):
  11. iv = ciphertext[:16]
  12. c = ciphertext[16:]
  13. cipher = AES.new(key, AES.MODE_CBC, iv)
  14. plain = cipher.decrypt(c)
  15. #print('Debug: padded msg: %s' % plain.encode('hex'))
  16. if ispkcs7(plain):
  17. return remove_padding(plain)
  18. return False
  19. def remove_padding(pt):
  20. pad_len = int(ord(pt[-1]))
  21. return pt[:-pad_len]
  22. def ispkcs7(plaintext):
  23. l = len(plaintext)
  24. c = ord(plaintext[l-1])
  25. if (c > 16) or (c < 1):
  26. return False
  27. if plaintext[l-c:] != chr(c) * c:
  28. return False
  29. return True
  30. def encr(plaintext):
  31. iv = ''.join([chr(randint(0,0xff)) for x in range(16)])
  32. cipher = AES.new(key, AES.MODE_CBC, iv)
  33. ciphertext = cipher.encrypt(pkcs7(plaintext))
  34. return iv + ciphertext
  35. def pkcs7(plaintext):
  36. print("PKCS#7")
  37. print plaintext
  38. if len(plaintext) % 16 == 0:
  39. pad = "\x00" * 16
  40. else:
  41. padbytes = 16 - len(plaintext) % 16
  42. pad = padbytes * chr(padbytes)
  43. tmp= plaintext + pad
  44. print(tmp.encode('hex'))
  45. return plaintext + pad