【发布时间】:2019-10-29 23:57:18
【问题描述】:
我正在尝试 AES。我正在尝试完全在一个过程中传递一条加密消息:
import hashlib
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)
############################################
#This is where the examples are being tried
encrypted = str(encrypted).encode('unicode-escape')
###########################################
encryptedString = base64.encodebytes(encrypted)
print(encryptedString)
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)
我收到以下错误:预期的类似字节的对象,而不是 str
基本上我正在尝试将字符串(字节字符串)转换为字节(字节字符串)。通常我会传递前面带有 b 的字符串,例如: b'?j\xf5\xd3\x8bP\xe5\xd5\xcd\xa2]\xa7\xf7\xc7\x9cO\x92\x0f\xdb}\xf5N\xb94J\xc7\x13'
但在这种情况下,加密消息将作为字符串接收,并且必须转换为字节。
我试过了:
encrypted = str(encrypted).encode('utf-8')
加密 = 字节(str(加密),'utf-8')
encrypted = str(encrypted).encode('unicode-escape')
这些示例不会产生错误,但脚本会再次对其进行加密而不是解密。
【问题讨论】:
-
encrypted = str(encrypted).encode('unicode-escape')我不知道你想在那里做什么,但这是错误的,所以摆脱这条线。encrypted = base64.decodebytes(encryptedString)现在,如果您想将其打印出来或通过文本通道传输,这很有意义。 -
正如 James 所建议的,如果您完全省略该行会怎样?如果您的 base 64 编码器无法处理字节字符串,您可能需要使用另一个编码器。毕竟你最不想要的就是内存中的另一个副本。
-
所以这个脚本只是完整脚本的编辑版本。有两个单独的脚本:发送者和阅读者。它们都独立运行,字节对象将被捕获为字符串。
-
snakecharmerb 是正确的!
标签: python encryption cryptography aes