Skip to content

Instantly share code, notes, and snippets.

@rgov
Created July 16, 2014 16:21
Show Gist options
  • Save rgov/22728617500e20081480 to your computer and use it in GitHub Desktop.
Save rgov/22728617500e20081480 to your computer and use it in GitHub Desktop.
def decrypt_and_compare(data, key, iv, expected):
unpad = lambda s: s[0:-ord(s[-1])]
aes = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv)
# Decrypt each block of data, except for the last one
for i in xrange(0, len(data) - 16, 16):
if aes.decrypt(data[i:i+16]) != expected[i:i+16]:
return False
# Decrypt the last block of data, unpad, and compare
decrypted = unpad(aes.decrypt(data[-16:]))
return len(decrypted) == 0 or decrypted == expected[-16:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment