可以从base64字符串中删除等号吗? [英] Is it ok to remove the equal signs from a base64 string?

查看:772
本文介绍了可以从base64字符串中删除等号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要编码为base64的字符串,以节省空间.如果我最后删除等号,那有什么大不了的?这会大大降低熵吗?我该怎么做才能确保结果字符串的长度是固定的?

I have a string that I'm encoding into base64 to conserve space. Is it a big deal if I remove the equal sign at the end? Would this significantly decrease entropy? What can I do to ensure the length of the resulting string is fixed?

>>> base64.b64encode(combined.digest(), altchars="AB")
'PeFC3irNFx8fuzwjAzAfEAup9cz6xujsf2gAIH2GdUM='

谢谢.

推荐答案

查看您的代码:

>>> base64.b64encode(combined.digest(), altchars="AB")
'PeFC3irNFx8fuzwjAzAfEAup9cz6xujsf2gAIH2GdUM='

在base64中编码的字符串是名为digest()的函数的结果.如果摘要功能产生固定长度的值(例如,如果要计算MD5或SHA1摘要),则b64encode的参数将始终为相同长度.

The string that's being encoded in base64 is the result of a function called digest(). If your digest function is producing fixed length values (e.g. if it's calculating MD5 or SHA1 digests), then the parameter to b64encode will always be the same length.

如果以上是正确的,则可以删除尾随等号,因为它们的数量总是相同.如果这样做,只需在解码之前在字符串上附加相同数量的等号即可.

If the above is true, then you can strip of the trailing equals signs, because there will always be the same number of them. If you do that, simply append the same number of equals signs to the string before you decode.

如果摘要不是固定长度,则修剪等号是不安全的.

If the digest is not a fixed length, then it's not safe to trim the equals signs.

:您似乎正在使用SHA-256摘要? SHA-256摘要为256位(或32字节). 32个字节是10组,每组3个,外加两个.您将从有关填充的Wikipedia部分中看到的;那意味着你总是有一个尾随的等式.如果它是SHA-256,则可以剥离它,只要您记得在解码之前再次添加它即可.

Looks like you might be using a SHA-256 digest? The SHA-256 digest is 256 bits (or 32 bytes). 32 bytes is 10 groups of 3, plus two left over. As you'll see from the Wikipedia section on padding; that'd mean you always have one trailing equals. If it is SHA-256, then it'd be OK to strip it, so long as you remember to add it again before decoding.

这篇关于可以从base64字符串中删除等号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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