我正在使用PyAES制作AES加密/解密程序,当我打印输出时,它看起来像这样:
b'\xb6\xd52#\xb1\xd5a~.L\xc2M\x83U\xb3\xf6'
(已加密)
b'TextMustBe16Byte'
(纯文本)
我想消除b和撇号,以便前端看起来更干净。
我的代码:
import pyaes
import os
# A 256 bit (32 byte) key
key = os.urandom(32)
# For some modes of operation we need a random initialization vector
# of 16 bytes
iv = os.urandom(16)
aes = pyaes.AESModeOfOperationCBC(key, iv = iv)
plaintext = "TextMustBe16Byte"
ciphertext = aes.encrypt(plaintext)
# '\xd6:\x18\xe6\xb1\xb3\xc3\xdc\x87\xdf\xa7|\x08{k\xb6'
print(ciphertext)
# The cipher-block chaining mode of operation maintains state, so
# decryption requires a new instance be created
aes = pyaes.AESModeOfOperationCBC(key, iv = iv)
decrypted = aes.decrypt(ciphertext)
print(decrypted)
答案 0 :(得分:0)
bytes
对象使用其repr
(带有b
和引号)。如果要转换为等效的字符串,最简单的方法是将它们decode
latin-1
(latin-1
是一种1-1编码,它将每个字节转换为相同的Unicode序数。值)。
所以只需更改:
print(ciphertext)
收件人:
print(ciphertext.decode('latin-1'))
和:
print(decrypted)
收件人:
print(decrypted.decode('latin-1'))
aes.encrypt
似乎在latin-1
中隐式“编码”输入字符串(it's doing [ord(c) for c in text]
,它实际上是编码为latin-1
,而没有实际检查字符是否合法{ {1}};序数大于255的字符在以后的处理中可能会爆炸),因此,鉴于模块的限制,这是一个合理的解决方案。如果要支持非拉丁1输入,请确保将latin-1
的输入encode
使用更好的编码(例如encrypt
),并在另一端使用相同的编码进行解码(尽管无论如何,您都希望使用utf-8
作为密文;它是原始的随机字节,因此任何其他编码都没有意义。)