python解密AES

时间:2017-11-02 08:28:56

标签: python encryption aes

这是我的代码:

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

1 个答案:

答案 0 :(得分: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))