gpt4 book ai didi

Python 3.5 base64解码似乎不正确?

转载 作者:行者123 更新时间:2023-11-30 22:36:00 24 4
gpt4 key购买 nike

Python 3.5 base64模块有一个方法,standard_b64decode()用于从 Base64 解码字符串,返回 bytes目的。

当我运行base64.standard_b64decode("wc==")时输出是b\xc1 。当你使用base64编码"\xc1"时,你得到"wQ==" 。看起来解码功能有错误。其实我觉得"wc=="是一个无效的 base64 编码字符串,按此推理:

  1. wc==== 结尾,这意味着它是从单个输入字节生成的。

  2. 'w'对应的值和'c'在常规的 base64 字母表中分别是 4828 ,这意味着它们的 6 位表示分别是 110000011100

  3. 将这些连接起来,前 8 位是 11000001 ,即\xc1 ,但剩余位 ( 1100 ) 不为零,因此不可能由在 Base64 编码期间执行的填充过程生成,因为这仅附加值为 0 的位。 ,这意味着这些额外的 1无法通过有效的 Base64 编码生成位 -> 该字符串不是有效的 Base64 编码字符串。

我认为对于任何以==结尾的base64编码的4个字符 block 都是如此。当第二个字符的最后 4 位中的任何一个为 1 时.

我非常确信这是正确的,但我的经验比 Python 开发人员要少。

任何人都可以确认上述内容,或者解释为什么它是错误的(如果确实如此)?

最佳答案

Base64 标准由 RFC 4648 定义。您的问题由§3.5回答:

Canonical Encoding

The padding step in base 64 and base 32 encoding can, if improperly implemented, lead to non-significant alterations of the encoded data. For example, if the input is only one octet for a base 64 encoding, then all six bits of the first symbol are used, but only the first two bits of the next symbol are used. These pad bits MUST be set to zero by conforming encoders, which is described in the descriptions on padding below. If this property do not hold, there is no canonical representation of base-encoded data, and multiple base- encoded strings can be decoded to the same binary data. If this property (and others discussed in this document) holds, a canonical encoding is guaranteed.

In some environments, the alteration is critical and therefore decoders MAY chose to reject an encoding if the pad bits have not been set to zero.

MAY 的含义由RFC 2119 定义。 :

MAY This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a particular marketplace requires it or because the vendor feels that it enhances the product while another vendor may omit the same item.

因此,Python 没有义务按照标准拒绝非规范编码。

关于Python 3.5 base64解码似乎不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44347819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com