I don't know if i am asking a silly question but I want to know whether Convert.ToBase64String function in .NET returns the same length as it's source byte size or is it different? I wanted to try out the article from MSDN itself How To: Use Forms Authentication with SQL Server 2000 to hash my password but I found out that the function they used to create salt string is returning 3 more length than it is supposed to return. To clarify here is the code in that article.
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);
}
Encoded size increase This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase). The increase may be larger if the encoded data is small.
The short answer is yes, unique binary/hex values will always encode to a unique base64 encoded string. BUT, multiple base64 encoded strings may represent a single binary/hex value. This is because hex bytes are not aligned with base64 'digits'.
Base64 is apparently wasteful because we use just 64 different values per byte, whereas a byte can represent 256 different characters. That is, we use bytes (which are 8-bit words) as 6-bit words. There is a waste of 2 bits for each 8 bits of transmission data.
ToBase64String(Byte[], Int32, Int32) Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits. Parameters specify the subset as an offset in the input array, and the number of elements in the array to convert.
No, Base64 returns 4 bytes output for 3 bytes input, rounded up (padded with =) to the next 4-byte boundary.
int outputLength = ((inputLength+2)/3)*4
That's because it only uses 6 bits (basically a number 0-63) per byte in order to only use ASCII chars which are not control chars and in the 7-bit range. Therefore, you get 3*8 => 4*6 bits when encoding data with Base64.
base-64 rarely returns a string of the same length as the input. Essentially, it is only using 6 of the available 8 bits, so large messages (in particular) will require an extra 1/3 volume. There are a few packing bytes (usually "=") at the end to make the message unambiguous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With