删除尾随的“="base64编码时 [英] Remove trailing "=" when base64 encoding

查看:30
本文介绍了删除尾随的“="base64编码时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,每当我对字符串进行 base64 编码时,都会在末尾附加一个=".我可以删除这个字符,然后通过添加回来可靠地解码它,还是这很危险?换句话说,是="始终附加,还是仅在某些情况下附加?

I am noticing that whenever I base64 encode a string, a "=" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is this dangerous? In other words, is the "=" always appended, or only in certain cases?

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

I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.

推荐答案

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

The = is padding. <!------------>

维基百科

一个额外的填充字符是分配的可用于强制编码输出为整数4 个字符的倍数(或等效地,当未编码的二进制text 不是 3 个字节的倍数);这些填充字符必须是解码时丢弃但仍然允许计算有效未编码文本的长度,当它的输入二进制长度不会是3 个字节的倍数(最后一个非填充字符通常被编码,使得它代表的最后一个 6 位块最少会被零填充有效位,最多两个填充字符可能出现在末尾编码流).

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.

If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.
Note that the data will not be valid Base64 in transport.

另外,另一位用户指出(与 PHP 用户相关):

Also, Another user pointed out (relevant to PHP users):

请注意,在 PHP 中 base64_decode 将接受没有填充的字符串,因此如果您将其删除以稍后在 PHP 中处理它,则无需将其添加回来.– Mahn 2014 年 10 月 16 日 16:33

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,您可以安全地去除填充和解码,无需花哨的计算.

So if your destination is PHP, you can safely strip the padding and decode without fancy calculations.

这篇关于删除尾随的“="base64编码时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆