2

我正在尝试在 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)
4

1 回答 1

1

“ascii 编码”是什么意思?如您所知,我的代码需要 base64 输入并产生 base64 输出。删除对 and 函数的调用将b64decode允许您传入原始数据,然后由您将来自 Java 的输入解码为原始字节。b64encodeencryptdecrypt

于 2011-09-27T11:08:48.537 回答