base64编码和解码问题!=b

2024-03-29 14:03:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中给出了这个例子

sample = '5PB37L2CH5DUDWN2SUOYE6LJPYCJBFM5N2FGVEHF7HD224UR52KB===='
a = base64.b32decode(sample)
b = base64.b32encode(a)

为什么会这样

样品!=b?在

但在哪里

^{pr2}$

那么

样本==b


Tags: sample样品例子样本base64pr2b32decodeb32encode
2条回答

你得到的第一个样本是无效的base64。在

摘自维基:

When the number of bytes to encode is not divisible by 3 (that is, if there are only one or two bytes of input for the last block), then the following action is performed: Add extra bytes with value zero so there are three bytes, and perform the conversion to base64. If there was only one significant input byte, only the first two base64 digits are picked, and if there were two significant input bytes, the first three base64 digits are picked. '=' characters might be added to make the last block contain four base64 characters.

http://en.wikipedia.org/wiki/Base64#Examples

编辑:

摘自RFC 4648:

Special processing is performed if fewer than 24 bits are available
at the end of the data being encoded. A full encoding quantum is
always completed at the end of a quantity. When fewer than 24 input
bits are available in an input group, bits with value zero are added
(on the right) to form an integral number of 6-bit groups. Padding
at the end of the data is performed using the '=' character.

4乘以8bits(the='s)(在你的sample末尾)超过了24位,所以它们至少是不必要的。(不确定sample是什么数据类型,但找出它的大小乘以字符数除以24)

关于您的特定sample

基本编码读取24位块,只需要在基字符串末尾添加“=”填充字符,就可以使将字符串拆分为24位块后剩下的部分变为“24大小”,这样解码器就可以对其进行解析。 由于字符串末尾的====值超过24位,因此它们是无用的,因此:无效。。。在

首先,让我们弄清楚:你的问题是关于base32,而不是base64。在

你的原始样品有点太长了。结尾有4=填充,这意味着至少有20位填充。位数必须是8的倍数,所以它实际上是24位。base32中B的编码是1,这意味着设置了其中一个填充位。这违反了规范,该规范规定所有的填充位必须清除。解码完全丢弃位,编码产生正确的值A,而不是{}。在

相关问题 更多 >