python解密AES

问题描述 投票:0回答:1

这是我的代码:

from Crypto.Cipher import AES
from Crypto import Random
import base64

Plain_text = "Text"
random = Random.new()
IV = random.read(AES.block_size)
KEY = base64.b64encode(random.read(AES.key_size[0]))
Cipher = AES.AESCipher(KEY, AES.MODE_CFB, IV)
print "Key:", KEY

Encrypting = Cipher.encrypt(Plain_text)
print "Encrypting:\n",Encrypting


#KEY2 = base64.b64decode(KEY)
#IV2 = random.read(AES.block_size)
#print "KEY2:", KEY2
Cipher2 = AES.AESCipher(base64.b64decode(KEY), AES.MODE_CFB, IV)
Decrypting = Cipher2.decrypt(Encrypting)
print "Decrypting:\n", Decrypting

脚本输出:

Output is:
Key: VYy9unePPuKiQHwVcqkJzA==
Encrypting:
�F!C
Decrypting:
���

为什么脚本无法解密?

OS = Ubuntu 16.04

Python Version = 2.7.12
python encryption aes
1个回答
0
投票

提供给 AES 函数的密钥应为二进制格式。在您的情况下,您首先将密钥编码为 base-64。在加密中,看来你不小心使用了这个编码字符串作为密钥。

固定代码片段:

from Crypto.Cipher import AES
from Crypto import Random
import base64

plaintext = "Text"
random = Random.new()
iv = random.read(AES.block_size)
key = random.read(AES.key_size[0])
cipher = AES.AESCipher(key, AES.MODE_CFB, iv)

key_b64 = base64.b64encode(key)
print ("Key: {}".format(key_b64))

ciphertext = cipher.encrypt(plaintext)
print("Encrypting: {}".format(ciphertext))
© www.soinside.com 2019 - 2024. All rights reserved.