我注意到每当我对字符串进行 Base64 编码时,都会在末尾附加一个“=”。我可以删除这个字符,然后通过将其添加回去来可靠地解码它吗?或者这很危险吗?换句话说,“=”总是附加,还是仅在某些情况下附加?
我希望编码的字符串尽可能短,这就是为什么我想知道是否可以删除“=”字符并在解码之前将其添加回来。
最佳答案
=
是填充。 <!------------>
An additional pad character is allocated which may be used to force the encoded output into an integer multiple of 4 characters (or equivalently when the unencoded binary text is not a multiple of 3 bytes) ; these padding characters must then be discarded when decoding but still allow the calculation of the effective length of the unencoded text, when its input binary length would not be a multiple of 3 bytes (the last non-pad character is normally encoded so that the last 6-bit block it represents will be zero-padded on its least significant bits, at most two pad characters may occur at the end of the encoded stream).
如果您控制另一端,则可以在传输时将其移除,然后在解码之前重新插入(通过检查字符串长度)。
请注意,数据在传输中不会是有效的 Base64。
另外,另一位用户指出(与 PHP 用户相关):
Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back. – Mahn Oct 16 '14 at 16:33
因此,如果您的目标是 PHP,您可以安全地去除填充并进行解码,而无需进行复杂的计算。
关于base64 - Base64 编码时删除尾随 "=",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4492426/