from Crypto.Cipher import AES
from random import randint


key = "aaaabbbbccccdddd"

def decr(ciphertext):
  iv = ciphertext[:16]
  c = ciphertext[17:]
  cipher = AES.new(key, AES.MODE_CBC, iv)
  return ispkcs7(cipher.decrypt(c))

""" decrypts the ct and returns it when padding is ok, else retuirn False """
def decrypt(ciphertext):
  iv = ciphertext[:16]
  c = ciphertext[16:]
  cipher = AES.new(key, AES.MODE_CBC, iv)

  plain = cipher.decrypt(c)
  #print('Debug: padded msg: %s' % plain.encode('hex'))
  if ispkcs7(plain):
    return remove_padding(plain)
  return False


def remove_padding(pt):
    pad_len = int(ord(pt[-1]))
    return pt[:-pad_len]


def ispkcs7(plaintext):
  l = len(plaintext)
  c = ord(plaintext[l-1])

  if (c > 16) or (c < 1):
    return False
  if plaintext[l-c:] != chr(c) * c:
    return False

  return True


def encr(plaintext):
  iv = ''.join([chr(randint(0,0xff)) for x in range(16)])
  cipher = AES.new(key, AES.MODE_CBC, iv)
  ciphertext = cipher.encrypt(pkcs7(plaintext))
  return iv + ciphertext

def pkcs7(plaintext):
  print("PKCS#7")
  print plaintext
  if len(plaintext) % 16 == 0:
    pad = "\x00" * 16
  else:
    padbytes = 16 - len(plaintext) % 16
    pad = padbytes * chr(padbytes)
  tmp= plaintext + pad
  print(tmp.encode('hex'))
  return plaintext + pad

