Decrypt in Python an encrypted message in Java
I'm trying to decrypt in Python (with M2Crypto) an encrypted message generated in Java with this library
My code (which I actually found here) works decrypting messages encrypted by itself, but not from Java's library, I get the following error:
EVPError: 'wrong final block length'
I have tried both *aes_128_cbc* and *aes_128_ecb* and I get the same error.
I guess the failure is that Java's result is Ascii's encoded and Python's code is expecting some other encoding (as it works with base64) but I don't know where to make the change (in my Python's code). I'm open to use any other Python encryption library.
Thanks
import M2Crypto
from base64 import b64encode, b64decode
ENC=1
DEC=0
def AES_build_cipher(key, iv, op=ENC):
""""""""
return M2Crypto.EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op)
def AES_encryptor(key,msg, iv=None):
""""""
#Decode the key and iv
key = b64decode(key)
if iv is None:
iv = '\0' * 16
else:
iv = b64decode(iv)
# Return the encryption function
def encrypt(data):
cipher = AES_build_cipher(key, iv, ENC)
v = cipher.update(data)
v = v + cipher.final()
del cipher
v = b64encode(v)
return v
print "AES encryption successful\n"
ret开发者_如何学Curn encrypt(msg)
def AES_decryptor(key,msg, iv=None):
""""""
#Decode the key and iv
key = b64decode(key)
print key
print
if iv is None:
iv = '\0' * 16
else:
iv = b64decode(iv)
# Return the decryption function
def decrypt(data):
data = b64decode(data)
cipher = AES_build_cipher(key, iv, DEC)
v = cipher.update(data)
v = v + cipher.final()
del cipher
return v
print "AES dencryption successful\n"
return decrypt(msg)
if __name__ == "__main__":
result = AES_decryptor(b64encode(SECRET_KEY), msg=encrypted_message)
What does "ascii encoded" mean? As you know, my code expected base64 input and produced base64 output. Removing the calls to b64decode
and b64encode
in the encrypt
and decrypt
functions will let you pass in raw data, then it'll be up to you to decode the input from Java into raw bytes.
精彩评论