首页 > 解决方案 > 为什么 AES 不解密我的加密文本?

问题描述

ecb模式有bug吗?为什么我的程序即使我做了所有事情都无法工作......我被卡住了,请帮忙。

我加密的文本:你好世界

我的尝试:

from Crypto.Cipher import AES
import base64

key = '0123456789abcdef'
#this is the password that we are going to use to encrypt and decrpyt the text 

def encrypt(text):
    global key
    cipher = AES.new(key, AES.MODE_ECB)
    
    if len(text) %16!=0:
        while not len(text)%16==0:
            text=text+" "
    
    encrypted_text =cipher.encrypt(text)
    return encrypted_text.strip()


def decrypt(text):
    global key
    decipher = AES.new(key, AES.MODE_ECB)
    
    if len(text)%16!=0:
        while len(text)%16!=0:
            text=str(text)+" "
    
    return decipher.decrypt(text).strip()
   
text=input("Enter encrypted text here : ")
#b'XhXAv\xd2\xac\xa3\xc2WY*\x9d\x8a\x02'

print(decrypt(text))

输入 :

b'XhXAv\xd2\xac\xa3\xc2WY*\x9d\x8a\x02'

输出 :

b"yR\xca\xb1\xf6\xcal<I\x93A1`\x1e\x17R\xbb\xc8(0\x94\x19'\xb3QT\xeb\x9b\xfe\xc8\xce\xf4l9\x92\xe8@\x18\xf2\x85\xbe\x13\x00\x8d\xa8\x96M9"

所需输出:

hello world

标签: pythonpycryptoecb

解决方案


解密时不要填充密文。请注意,您可能需要在解密之后而不是之前删除填充。

from Crypto.Cipher import AES
from base64 import b64encode, b64decode

key = '0123456789abcdef'
#this is the password that we are going to use to encrypt and decrpyt the text 

def encrypt(text):
    global key
    cipher = AES.new(key, AES.MODE_ECB)
    if len(text) %16!=0:
        while not len(text)%16==0:
            text=text+" "
    encrypted_text =cipher.encrypt(text)
    return b64encode(encrypted_text).decode('UTF-8')

def decrypt(text):
    global key
    text = b64decode(text) # decode before decryption
    decipher = AES.new(key, AES.MODE_ECB)
    return decipher.decrypt(text).decode('UTF-8')

text = input("Please enter your text: ")
ciphertext = encrypt(text)
print(f'Ciphertext: {ciphertext}')
print(f'Decrypted ciphertet: {decrypt(ciphertext)}')

结果如下:

Please enter your text: hello world
Ciphertext: WGhYQXbSrKPCV1kqnYoCDQ==
Decrypted ciphertet: hello world 

更新:您还可以通过调用对密文进行编码b64encodebase64在这种情况下,您需要在解密之前通过调用进行解码b64decode。建议使用base64之类的编码,以方便在网络和Internet中传输密文。


推荐阅读