Convert.ToBase64String返回与源字节数组相同的长度吗?

Mya*_*tut 7 .net c# cryptography

我不知道我是否在问一个愚蠢的问题,但我想知道.NET中的Convert.ToBase64String函数是否返回与源字节大小相同的长度,还是不同?我想试试MSDN本身的文章如何:使用SQL Server 2000的表单身份验证来哈希我的密码,但我发现他们用来创建salt字符串的函数返回的长度比应该返回的长3.这里要澄清的是该文章中的代码.

private static string CreateSalt(int size)
{
   // Generate a cryptographic random number using the cryptographic
   // service provider
   RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
   byte[] buff = new byte[size];
   rng.GetBytes(buff);
   // Return a Base64 string representation of the random number
   return Convert.ToBase64String(buff);
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ero 14

不,Base64为3字节输入返回4字节输出,向上舍入(用=填充)到下一个4字节边界.

int outputLength = ((inputLength+2)/3)*4
Run Code Online (Sandbox Code Playgroud)

这是因为它每个字节仅使用6位(基本上是0-63),以便仅使用不是控制字符且在7位范围内的ASCII字符.因此,使用Base64编码数据时,您将获得3*8 => 4*6位.


Mar*_*ell 5

base-64很少返回与输入长度相同的字符串.本质上,它仅使用6个可用的8位,因此大的消息(特别是)需要额外的1/3音量.最后有一些打包字节(通常是"=")以使消息明确无误.


Fra*_*ger 2

字节字符串的 Base64 编码比字节字符串长,因为该字节字符串每个“位置”有 2^8 种可能性,而 Base 64 字符串每个位置只有 2^6 种可能性(这就是我们称之为 Base 64 的原因)。

想想对数和鸽子洞吧。以数字 5000 为例。为了将它存储在 256 进制中,您需要多少个位置(鸽子洞、字节)?

"Locations in base256" = ceil(log_2(5000) / 8) = ceil(1.54) = 2
Run Code Online (Sandbox Code Playgroud)

其中 log_2 告诉您需要多少位。现在有多少个base64?

"Locations in base64" = ceil(log_2(5000) / 6) = ceil(2.04) = 3
Run Code Online (Sandbox Code Playgroud)