python - 为什么 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
解决方案
解密时不要填充密文。请注意,您可能需要在解密之后而不是之前删除填充。
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
更新:您还可以通过调用对密文进行编码b64encode
,base64
在这种情况下,您需要在解密之前通过调用进行解码b64decode
。建议使用base64之类的编码,以方便在网络和Internet中传输密文。
推荐阅读
- c++ - 多文件类实现Cpp
- javascript - 动画精灵延迟,从左到右切换时
- architecture - 电路如何再次闭合?
- c# - 使用 c# 配置 WiFi 凭证
- python - OpenCV 视频捕获 - 输出甚至可能损坏的帧
- cassandra - Cassandra:Nodetool GossipInfo 和 Nodetool 状态中的替换节点显示
- javascript - 如何元素固定同步与浏览器滚动
- javascript - 如何将视频添加到我的网站,当您单击按钮时播放?
- excel - Access VBA Excel:格式化 Excel 和范围应用程序/对象错误
- compilation - 构建依赖和运行时依赖有什么区别