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