FromBase64字符串的长度必须是多个还是4? [英] FromBase64 string length must be multiple or 4 or not?

查看:358
本文介绍了FromBase64字符串的长度必须是多个还是4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,base64编码的字符串(即encode的输出)必须始终为4的倍数.

according to my understanding, a base64 encoded string (ie the output of encode) must always be a multiple of 4.

c#Convert.FromBase64String表示其输入必须为4的倍数.

the c# Convert.FromBase64String says that its input must be a multiple of 4

但是,如果我给它一个25个字符串,它不会抱怨

However if I give it a 25 character string it doesnt complain

[convert]::FromBase64String("ei5gsIELIki+GpnPGyPVBA==")
[convert]::FromBase64String("1ei5gsIELIki+GpnPGyPVBA==")

都工作. (第一个是24,第二个是25)

both work. (The first one is 24 , second is 25)

[convert]::FromBase64String("11ei5gsIELIki+GpnPGyPVBA==")

长度无效的异常失败

我认为这是c#库中的错误,但我只想确保-我正在编写嗅探字符串以查看它们是否为有效的base64字符串的代码,并且我想确保自己了解什么是有效的字符串看起来(一种可能的实现方式是将字符串提供给system.convert并查看它是否抛出了-为什么要重新发明完美的代码)

I assume this is a bug in the c# library but I just want to make sure - I am writing code that is sniffing strings to see if they are valid base64 strings and I want to be sure that I understand what a valid one looks like (one possible implementation was to give the string to system.convert and see if it threw - why reinvent perfectly good code)

推荐答案

是的,这是一个缺陷(又名bug).它是由于内部助手函数FromBase64_ComputeResultLength()中的性能优化而开始计算的,该函数可计算byte []结果的长度.它具有此评论(已编辑为适合):

Yes, this is a flaw (aka bug). It got started due to a perf optimization in an internal helper function named FromBase64_ComputeResultLength() which calculates the length of the byte[] result. It has this comment (edited to fit):

   // For legal input, we can assume that 0 <= padding < 3. But it may be 
   // more for illegal input.
   // We will notice it at decode when we see a '=' at the wrong place.

我们会注意到"的说明并不完全准确,如果不期望解码器,则将其标记为"=",但无法检查是否有太多. 25个字符的字符串就是这种情况.

The "we will notice" remark is not entirely accurate, the decoder does flag an '=' if one isn't expected but it fails to check if there's one too many. Which is the case for the 25-char string.

您可以在connect.microsoft.com上报告该问题,但没有类似的现有报告.请注意,由于更改将破坏现有的程序,这些程序现在可以成功解析错误的base64字符串,因此Microsoft几乎不可能在短期内对其进行修复.通常,它需要对.NET进行重大更新才能消除此类问题,就像针对.NET 4.0所做的那样,因此afaik即将问世.

You can report the problem at connect.microsoft.com, I don't see an existing report that resembles it. Do note that it is fairly unlikely that Microsoft can actually fix it any time soon since the change is going to break existing programs that now successfully parse bad base64 strings. It normally requires a major .NET release update to get rid of such problems, like it was done for .NET 4.0, there isn't one on the horizon afaik.

但是,是的,一种简单的解决方法是使用%运算符检查字符串长度是否可以被4整除.

But yes, the simple workaround for you is to check if the string length is divisible by 4, use the % operator.

这篇关于FromBase64字符串的长度必须是多个还是4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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