gpt4 book ai didi

java - 在 Python 中解密 Java 中的加密消息

转载 作者:行者123 更新时间:2023-11-30 11:51:15 36 4
gpt4 key购买 nike

我正在尝试在 Python 中(使用 M2Crypto)解密一条在 Java 中使用此 library 生成的加密消息

我的代码(我实际上是在这里找到的)可以解密自己加密的消息,而不是来自 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)

最佳答案

“ascii 编码”是什么意思?如您所知,我的代码需要 base64 输入并生成 base64 输出。去掉encryptdecrypt函数中对b64decodeb64encode的调用,就可以传入原始数据,然后将来自 Java 的输入解码为原始字节将取决于您。

关于java - 在 Python 中解密 Java 中的加密消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567520/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com