簡體   English   中英

用Python解密Java中的加密消息

[英]Decrypt in Python an encrypted message in Java

我正在嘗試使用此在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)

“ ascii編碼”是什么意思? 如您所知,我的代碼期望base64輸入並產生base64輸出。 刪除encryptdecrypt函數中對b64decodeb64encode的調用將使您傳遞原始數據,然后由您決定將Java中的輸入解碼為原始字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM