当我传入 64 个字节时,为什么 C# Convert.ToBase64String() 给出的长度为 88?

发布于 2025-01-01 16:02:42 字数 618 浏览 3 评论 0原文

我试图理解以下内容:

如果我声明 64 字节作为数组长度(缓冲区)。当我转换为 Base 64 字符串时,它显示长度为 88。长度不应该仅为 64,因为我传递的是 64 个字节?我可能完全误解了它的实际工作原理。如果是这样,请您解释一下。

//Generate a cryptographic random number
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

// Create byte array
byte[] buffer = new byte[64];

// Get random bytes
rng.GetBytes(buffer);

// This line gives me 88 as a result. 
// Shouldn't it give me 64 as declared above?
throw new Exception(Convert.ToBase64String(buffer).Length.ToString());

// Return a Base64 string representation of the random number
return Convert.ToBase64String(buffer);

I'm trying to understand the following:

If I am declaring 64 bytes as the array length (buffer). When I convert to a base 64 string, it says the length is 88. Shouldn't the length only be 64, since I am passing in 64 bytes? I could be totally misunderstanding how this actual works. If so, could you please explain.

//Generate a cryptographic random number
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

// Create byte array
byte[] buffer = new byte[64];

// Get random bytes
rng.GetBytes(buffer);

// This line gives me 88 as a result. 
// Shouldn't it give me 64 as declared above?
throw new Exception(Convert.ToBase64String(buffer).Length.ToString());

// Return a Base64 string representation of the random number
return Convert.ToBase64String(buffer);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自由如风 2025-01-08 16:02:43

不,base-64 编码使用整个字节来表示正在编码的数据的六位。丢失的两位是仅使用字母数字、加号和斜杠作为符号的代价(基本上,不包括表示纯 ASCII/UTF-8 编码中不可见或特殊字符的数字)。您得到的结果是 (64*4/3) 四舍五入到最近的 4 字节边界。

No, base-64 encoding uses a whole byte to represent six bits of the data being encoded. The lost two bits is the price of using only alphanumeric, plus and slash as your symbols (basically, excluding the numbers representing not visible or special characters in plain ASCII/UTF-8 encoding). The result that you are getting is (64*4/3) rounded up to the nearest 4-byte boundary.

瑾夏年华 2025-01-08 16:02:43

Base64编码将3个八位字节转换为4个编码字符;所以

(64/3)*4 ≈ (22*4) = 88 字节。

阅读此处。

Base64 encoding converts 3 octets into 4 encoded characters; therefore

(64/3)*4 ≈ (22*4) = 88 bytes.

Read here.

夏末染殇 2025-01-08 16:02:43

既然我传入的是 64 个字节,长度不应该只有 64 吗?

不。您正在以 Base256 表示法传递 64 个令牌。 Base64 每个令牌的信息较少,因此需要更多令牌。 88 听起来不错。

Shouldn't the length only be 64, since I am passing in 64 bytes?

No. You are passing 64 tokens in Base256 notation. Base64 has less information per token, so it needs more tokens. 88 sounds about right.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文