【问题标题】:why python cryptodome using latin-1 to encode and decode string?为什么 python cryptodome 使用 latin-1 编码和解码字符串?
【发布时间】:2018-10-17 05:51:08
【问题描述】:

当我查看Cryptodome的代码时,我发现latin-1编码与utf-8会导致一些我们不想要的副作用的注释一起使用。

例如,Cryptodome 中的py3compat.py 对字符串进行如下编码和解码。

def tobytes(s):
    if isinstance(s,bytes):
        return s
    else:
        if isinstance(s,str):
            return s.encode("latin-1")
        else:
            return bytes([s])
def tostr(bs):
    return bs.decode("latin-1")

【问题讨论】:

标签: python cryptography


【解决方案1】:

原因可能很简单。 Python 将字符串作为字节处理。默认情况下,Python 2 应该只使用 ASCII 源代码,但很可能存在 Latin-1 编码。字节的文字表示取决于源文件的编码。

因此,您需要使用 Latin-1 以尽可能兼容旧应用程序生成的字节表示。当然,现在通常最好默认为 UTF-8。我强烈建议将字符显式编码为 UTF-8,而不是依赖任何默认值。

这存在于名为py3compat.py 的文件中并非巧合。

【讨论】:

  • 感谢您的大力帮助!
猜你喜欢
  • 2019-12-09
  • 1970-01-01
  • 2012-01-07
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
相关资源
最近更新 更多