我正在尝试使用PyCrypto.AES
进行加密和解密试验,当我尝试解密时,我会TypeError: 'str' does not support the buffer interface
我找到了一些解决方案,我必须编码或使用字符串,但我无法弄清楚如何使用它。
AESModule.py
from Crypto.Cipher import AES
#base64 is used for encoding. dont confuse encoding with encryption#
#encryption is used for disguising data
#encoding is used for putting data in a specific format
import base64
# os is for urandom, which is an accepted producer of randomness that
# is suitable for cryptology.
import os
def encryption(privateInfo,secret,BLOCK_SIZE):
#32 bytes = 256 bits
#16 = 128 bits
# the block size for cipher obj, can be 16 24 or 32. 16 matches 128 bit.
# the character used for padding
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
# function to pad the functions. Lambda
# is used for abstraction of functions.
# basically, its a function, and you define it, followed by the param
# followed by a colon,
# ex = lambda x: x+5
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
# generate a randomized secret key with urandom
#secret = os.urandom(BLOCK_SIZE)
print('Encryption key:',secret)
# creates the cipher obj using the key
cipher = AES.new(secret)
# encodes you private info!
encoded = EncodeAES(cipher, privateInfo)
print('Encrypted string:', encoded)
return(encoded)
def decryption(encryptedString,secret):
PADDING = '{'
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
#Key is FROM the printout of 'secret' in encryption
#below is the encryption.
encryption = encryptedString
cipher = AES.new(secret)
decoded = DecodeAES(cipher, encryption)
print(decoded)
test.py
import AESModule
import base64
import os
BLOCK_SIZE = 16
key = os.urandom(BLOCK_SIZE)
c = AESRun2.encryption('password',key,BLOCK_SIZE)
AESRun2.decryption(c,key)
答案 0 :(得分:2)
字符串(str
)是文本。加密不处理文本,它以字节(bytes
)。
实际上,在必要时插入.encode
和.decode
来调用两者之间的转换。我推荐使用UTF-8编码。
在您的情况下,因为您已经将密文编码和解码为base-64,这是另一个字节/文本转换,您只需要对明文进行编码和解码。在将字符串传递给加密函数时,使用.encode("utf-8")
对字符串进行编码,并在将其从解密函数中取出时使用.decode("utf-8")
解码最终结果。
如果您正在阅读示例或教程,请确保它们适用于Python 3.在Python 2中str
是一个字节字符串,将它用于文本和字节是很常见的,这非常令人困惑。在Python 3中,他们修复了它。