试图了解Python的AES方法

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

[我希望使用Python3的Crypto.Cipher在CTR模式下使用AES。实际的问题是我有一个二进制数字数组(字符串格式为“ 0/1”),并且希望使用AES-CTR对其进行加密/解密。在查看this文章之后,我尝试开发以下附加的代码。

from Crypto.Cipher import AES
import os
import sys

secret = os.urandom(16)
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret)

msg = "Hello World"

#string-->bytes
bytes_msg = str.encode(msg)
print(msg + " > 2bytes > " + str(bytes_msg))

#bytes-->encrypt
encrypted_bytes_msg = crypto.encrypt(bytes_msg)
print(" > encryption > " + str(encrypted_bytes_msg))

#encrypt-->decrypt
decrypted_bytes_msg = crypto.decrypt(encrypted_bytes_msg)
print(" > decryption > " + str(decrypted_bytes_msg))

#bytes-->string
#decrypted_msg = decrypted_bytes_msg.decode() # <= !ERROR HERE!
#print(" > msg > " + decrypted_msg)

我当时期望看到类似以下内容的东西:

Hello World> 2bytes>“ b'Hello World'>加密>#JibberishText#>解密> b'Hello World'> Hello World

此运行的实际结果是:

Hello World> 2bytes> b'Hello World'>加密> b'\ x8eo \ xfc` \ xeck \ xcf \ r4 \ x1fS'>解密> b'\ xc7 \ x93 \ x8a \ x1dK \ xad \ xc5 \ x9d8 \ x9c \ x18'

Also:如果我不注释掉最后几行,则会出现以下错误:

文件“ aes.py”,第25行,在crypted_msg =解密字节_msg.decode()UnicodeDecodeError:“ utf-8”编解码器无法解码位置0的字节0x8e:无效的起始字节

您能帮助我了解模块的使用方式吗?

python-3.x cryptography aes pycrypto python-cryptography
1个回答
0
投票

您需要非常小心地使用此模块公开的原语,很容易做错事情并完全破坏密码系统

您的原样代码对我不起作用,因为counter parameter should be a Crypto.Util.Counter不能正常工作。这大概可以与某些版本的库一起使用,但对我而言不起作用。

就是说,您的代码永远都行不通,因为您需要“重置”加密和解密之间的密码,以便在这些操作中使用相同的计数器值。该问题的第二个counter答案有一个更好的示例,说明如何使用该模块

© www.soinside.com 2019 - 2024. All rights reserved.