【问题标题】:Does Convert.ToBase64String return the same length as it's source byte array?Convert.ToBase64String 是否返回与其源字节数组相同的长度?
【发布时间】:2010-10-25 17:07:28
【问题描述】:

我不知道我是否在问一个愚蠢的问题,但我想知道 .NET 中的 Convert.ToBase64String 函数是否返回与其源字节大小相同的长度,还是不同?我想尝试 MSDN 本身 How To: Use Forms Authentication with SQL Server 2000 的文章来散列我的密码,但我发现他们用来创建盐字符串的函数返回的长度比它应该返回的长度多 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);
}

【问题讨论】:

    标签: c# .net cryptography


    【解决方案1】:

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

    int outputLength = ((inputLength+2)/3)*4
    

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

    【讨论】:

    • 谢谢哥们。它真的帮助我解开尾随“=”的奥秘。
    【解决方案2】:

    base-64 很少返回与输入长度相同的字符串。本质上,它只使用了可用的 8 位中的 6 位,因此(特别是)大消息将需要额外的 1/3 体积。末尾有几个打包字节(通常是“=”)以使消息明确。

    【讨论】:

      【解决方案3】:

      字节字符串的base64编码比字节字符串长,因为该字节字符串每个“位置”有2^8种可能性,而base 64字符串每个位置只有2^6种可能性(这就是为什么我们称它为base 64).

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

      "Locations in base256" = ceil(log_2(5000) / 8) = ceil(1.54) = 2
      

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

      "Locations in base64" = ceil(log_2(5000) / 6) = ceil(2.04) = 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 2015-04-01
        相关资源
        最近更新 更多