在Python中解密Java加密消息

2 投票
1 回答
1598 浏览
提问于 2025-04-17 03:10

我正在尝试用Python(使用M2Crypto库)解密一个用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)

1 个回答

1

“ascii编码”是什么意思呢?你知道,我的代码是期待接收base64格式的输入,并且输出也是base64格式的。如果你把b64decodeb64encode这两个函数在encryptdecrypt中去掉,就可以直接传入原始数据了。这样的话,解码从Java传来的输入成原始字节就得靠你自己来做了。

撰写回答