base64 - Base64 编码时删除尾随 "="

标签 base64

我注意到每当我对字符串进行 Base64 编码时,都会在末尾附加一个“=”。我可以删除这个字符,然后通过将其添加回去来可靠地解码它吗?或者这很危险吗?换句话说,“=”总是附加,还是仅在某些情况下附加?

我希望编码的字符串尽可能短,这就是为什么我想知道是否可以删除“=”字符并在解码之前将其添加回来。

最佳答案

= 是填充。 <!------------>

Wikipedia

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/

相关文章:

css - webpack中如何处理base64图片?

java - 将大字符串写入文件的问题

c# - 在c#.net中将 'String'转换为MD5 'String'的Base64编码

javascript - 使用 Javascript 将 <img> src 设置为 Base64 编码的图像失败

python - 将 base64 编码的字符串转换为十六进制 int

Python:将 PDF 转换为 blob 再转换回 pdf 会导致损坏

javascript - CryptoJS.enc.Base64.stringify() 和普通 Base64 加密的区别

javascript - 二进制图像下载

ruby-on-rails - 使用 Prawn 从 Base64 生成带有图像的 PDF

php - 如何在服务器端将 Base64 字符串读取为文件,而不将其保存在 Web 服务器中,直接通过 PHP?