尝试使用 pycryptodome 3.4.2 通过 python 3 的 aes 加密来加密/解密文本
当然,我在互联网上找到了这个方法,并尝试根据我的需要更改它,但我得到的只是错误。
代码如下:
def aes():
#aes
print('1.Шифруем')
print('2.Дешифруем')
c = input('Ваш выбор:')
if int(c) == 1:
#shifr
os.system('clear')
print('Шифруем значит')
print('Введите текст, который хотите зашифровать')
text = input()
with open('Aes/plaintext.txt', 'wb') as f:
f.write(text.encode('utf-8'))
BLOCK_SIZE = 16
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
secret = os.urandom(BLOCK_SIZE)
with open('Aes/secret.bin', 'wb') as f:
f.write(secret)
cipher = AES.new(secret, AES.MODE_CFB)
with open('Aes/plaintext.txt', 'rb') as f:
text = f.read()
encoded = EncodeAES(cipher, text)
with open('Aes/ciphertext.bin', 'wb') as f:
f.write(encoded)
print (encoded)
if int(c) == 2:
os.system('clear')
print('Дешифруем значит')
PADDING = '{'
with open('Aes/ciphertext.bin', 'rb') as f:
encoded = f.read()
with open('Aes/secret.bin', 'rb') as keyfile:
secret = keyfile.read()
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
cipher = AES.new(secret, AES.MODE_CFB)
decoded = DecodeAES(cipher, encoded)
with open('Aes/plaintext.txt', 'w') as f:
f.write(str(decoded))
print(decoded)
但是当我尝试解密某些文本时,我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/tukanoid/Desktop/Enc_dec2/Enc_dec.py", line 475, in <module>
aes()
File "/home/tukanoid/Desktop/Enc_dec2/Enc_dec.py", line 178, in aes
encoded = EncodeAES(cipher, text)
File "/home/tukanoid/Desktop/Enc_dec2/Enc_dec.py", line 166, in <lambda>
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
File "/home/tukanoid/Desktop/Enc_dec2/Enc_dec.py", line 162, in <lambda>
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
TypeError: can't concat bytes to str
实际上,我不知道 lambda 做了什么,但我认为我因此而收到此错误。谢谢。
最佳答案
您正在将文本文件读取为 rb
,在 python 3 中返回一个 bytes
对象。
在函数中,您使用 str
对象进行填充,因此会出现错误。 Python 3 明确地将二进制数据与文本数据分开,这是 Python 2 没有做到的事情。
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
将 open('Aes/plaintext.txt', 'rb')
更改为 open('Aes/plaintext.txt', 'r')
和你'两边都会得到ascii,这样就可以了。
(或将 PADDING
更改为 bytes('{',encoding="ascii")
或如 James 所说的 b"{"
)。
关于python-3.x - TypeError : can't concat bytes to str. Pycrypto Aes 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207259/