2
我想在Python(与M2Crypto)在Java中与此library解密在Python在Java中
我的代码(其实我发现这里)生成的加密消息进行解密加密消息的工作原理是加密解密的消息本身,而不是从Java的库中,我得到以下错误:
EVPError: 'wrong final block length'
我曾经尝试都* aes_128_cbc *和* aes_128_ecb *,我也得到了同样的错误。
我想失败的原因是Java的结果是Ascii的编码,而Python的代码需要其他一些编码(因为它与base64一起工作),但我不知道在哪里进行更改(在我的Python代码中)。我打算使用任何其他Python加密库。
感谢
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"
return 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)
你说得对,我已经删除了每一个b64encode/decode调用,但是我做了一些其他的修改以匹配ECB模式下的Java JCE加密结果(而不是CBC中的代码使用)。 在这两种方法中我都替换了* key.decode(“hex”)*的* key *值,加密方法中* v = b64encode(v)*替换为* v = v.encode(“hex”)* 。 – Imanol