.net Base64 编码数据最大大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7609135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encoded data maximum size
提问by dragonfly
I have a security mechanism that implements symmetric algorithm RijndaelManaged. I managed to find information what is the maximum size of encrypted data using RijndaelManagedfor particular IV. According to my calculations it will be 128 bytes. However I need to convert these 128 bytes to string using Base64. Is there a way to calculate maximum number of chars that Base64 encoding will use to encode input byte array of size 128?
我有一个实现对称算法RijndaelManaged的安全机制。我设法使用RijndaelManaged针对特定 IV找到了加密数据的最大大小的信息。根据我的计算,它将是 128 个字节。但是我需要使用 Base64 将这 128 个字节转换为字符串。有没有办法计算 Base64 编码将用于编码大小为 128 的输入字节数组的最大字符数?
Thanks,Pawel
谢谢,帕维尔
回答by Jon Skeet
Absolutely - Base64takes 4 characters to represent every 3 bytes. (Padding is applied for binary data which isn't an exact multiple of 3 bytes.) So 128 bytes will always be 172 characters. (The way to work this out is that base64 represents 6 bits in each character (26= 64); therefore 3 bytes = 24 bits = 4 base-64 characters.)
绝对 - Base64需要 4 个字符来表示每 3 个字节。(填充应用于不是 3 个字节的精确倍数的二进制数据。)因此 128 个字节将始终为 172 个字符。(解决这个问题的方法是 base64 表示每个字符中的 6 位 (2 6= 64);因此 3 个字节 = 24 位 = 4 个 base-64 字符。)
回答by Chris
A base 64 encoded string will use 4 characters for every 3 bytes (or part thereof). So 128 bytes would be 172 base 64 characters.
Base 64 编码的字符串每 3 个字节(或其一部分)将使用 4 个字符。所以 128 个字节将是 172 个基本 64 个字符。
回答by phayes
If you need to check this programatically, you can do so by checking the modulus. Here's some psudocode (no particular language) :
如果您需要以编程方式检查这一点,您可以通过检查模数来实现。这是一些伪代码(没有特定的语言):
function base64Inflation (numBytes)
minimumBase64Bytes = roundDown(numBytes / 3 * 4)
modulus = numberOfBytes % 3 // Assuming % is the modulo operator
if modulus == 0
return minimumBase64Bytes // Exact fit! No padding required.
else
return minimumBase64Bytes + 4 // Doesn't quite fit. We need to pad.
I've also implemented the same logic in golang:
我也在 golang 中实现了相同的逻辑:
回答by Josh
In Java:
在Java 中:
byte[] bytes = new byte[128];
int base64Length = bytes.length / 3 * 4; // Strictly integer division
if (bytes.length % 3 != 0)
{
base64Length += 4; // Extra padding characters will be added
}
System.out.println(bytes.length + " bytes will be encoded in " + base64Length + " characters.");
So, where the input bytes.length == 128, the output will be base64Length == 172characters.
因此,在输入的地方bytes.length == 128,输出将是base64Length == 172字符。

