【发布时间】:2019-09-11 05:14:33
【问题描述】:
我正在使用 python 和 AES 创建一个加密的聊天程序。我有一些从https://riptutorial.com/python/example/18926/symmetric-encryption-using-pycrypto收集的工作代码
import hashlib
import math
import os
import base64
from Crypto.Cipher import AES
IV_SIZE = 16 # 128 bit, fixed for the AES algorithm
KEY_SIZE = 32 # 256 bit meaning AES-256, can also be 128 or 192 bits
SALT_SIZE = 16 # This size is arbitrary
cleartext = b'Lorem ipsum'
password = b'highly secure encryption password'
salt = os.urandom(SALT_SIZE)
derived = hashlib.pbkdf2_hmac('sha256', password, salt, 100000,
dklen=IV_SIZE + KEY_SIZE)
iv = derived[0:IV_SIZE]
key = derived[IV_SIZE:]
encrypted = salt + AES.new(key, AES.MODE_CFB, iv).encrypt(cleartext)
print(encrypted)
############################################
# edit here: it is being pulled as a string instead of a byte string
encrypted = str(encrypted)
###########################################
# encrypted and enc2 should be the same, except for the salt.
encryptedString = base64.encodebytes(encrypted)
print(encryptedString) # <- this is what can be stored and fetched from mySQL
encrypted = base64.decodebytes(encryptedString) # <- get the bytes back
salt = encrypted[0:SALT_SIZE]
derived = hashlib.pbkdf2_hmac('sha256', password, salt, 100000,
dklen=IV_SIZE + KEY_SIZE)
iv = derived[0:IV_SIZE]
key = derived[IV_SIZE:]
cleartext = AES.new(key, AES.MODE_CFB, iv).decrypt(encrypted[SALT_SIZE:])
print(cleartext)
当我运行上面的代码时,我得到一个 TypeError: expected bytes-like object, not str
我尝试了几种方法:
字节(加密,'utf-8') 这种方法的问题在于它最终再次加密了字符串。
加密的.encode() 这和以前做的一样。
如何将字符串(字节字符串)转换为字节(字节字符串),而无需手动复制和粘贴字符串并在其前面放置 a b?
【问题讨论】:
-
编码不是加密。它可能看起来像胡言乱语,但事实并非如此。
-
我不明白。我试图避免手动复制和粘贴加密的输出。如何将其作为纯代码传递?
标签: python-3.x aes