【问题标题】:Why AES is not decrypting my encrypted text?为什么 AES 不解密我的加密文本?
【发布时间】:2020-12-02 19:29:55
【问题描述】:

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

我加密的文本:你好世界

我的尝试:

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

【问题讨论】:

  • 这是 python 2 还是 3? input 函数在两者之间做完全不同的事情。欧洲央行也不安全。

标签: python pycrypto ecb


【解决方案1】:

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

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之类的编码,方便网络和互联网的密文传输。

【讨论】:

  • 如果我将密文作为输入,为什么它不起作用(ValueError)? ciphertext=bytes(input("Enter ciphertext here : ), encoding="utf-8")
  • @RatnapalShende2 再次检查我的答案。
  • 非常感谢先生! @Pouya Esmaeili
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2014-04-19
  • 2012-02-24
  • 2011-04-01
相关资源
最近更新 更多