【问题标题】:PyAES output includes b and ''PyAES 输出包括 b 和 ''
【发布时间】:2019-03-07 21:02:48
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: python aes


    【解决方案1】:

    bytes 对象在正常字符串化时使用其repr(带有b 和引号)。如果要转换为等价的字符串,最简单的方法是将decode 转换为latin-1latin-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 而没有实际检查字符是否合法latin-1;序数大于255 的字符可能会在稍后的处理中爆炸),因此考虑到模块的限制,这是一个合理的解决方案。如果您想支持非 latin-1 输入,请确保将 encode 的输入以更好的编码(例如 utf-8)输入到 utf-8,并在另一端使用相同的编码进行解码(您会想要无论如何使用latin-1作为密文;它是原始随机字节,所以任何其他编码都没有意义)。

    【讨论】:

    • 返回错误UnicodeEncodeError: 'charmap' codec can't encode character '\x96' in position 0: character maps to <undefined>
    • @Thorn:听起来您的语言环境编码不知道如何表示该字符并且正在放弃。这是a known problem on Windows。您最好使用print(x.hex()) 来获取密文的十六进制输出(可能比尝试解码更有用)。
    • 这似乎是 Atom 上的脚本包的问题,​​因为使用专用的 Python 运行程序运行,它可以工作。然而,字符串“如果紫人食者是真实的……他们在哪里找到紫人吃?”显示错误ValueError: bytes must be in range(0, 256)
    • @Thorn:您的字符串中有一个省略号 (...),而 latin-1 中没有。这就是为什么我提到切换到utf-8 来编码初始字符串并解码最终字符串。
    猜你喜欢
    • 2012-02-21
    • 2014-03-26
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2019-03-07
    • 2017-01-21
    相关资源
    最近更新 更多