繁体   English   中英

为什么 AES 不解密我的加密文本?

[英]Why AES is not decrypting my encrypted text?

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'

output:

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"

所需 Output:

hello world

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

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 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM