Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# Convert.ToBase64String() give me 88 as a length when I'm passing in 64 bytes?

Tags:

c#

byte

bits

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);
like image 554
Frankie Avatar asked Feb 01 '12 20:02

Frankie


People also ask

Why does the letter C exist?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

Does the letter C exist?

C, or c, is the third letter in the English and ISO basic Latin alphabets. Its name in English is cee (pronounced /ˈsiː/), plural cees. This article contains phonetic transcriptions in the International Phonetic Alphabet (IPA).

Why is C not A or B?

Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.

Is C still used in 2022?

C is one of the earliest and most widely used programming languages. C is the fourth most popular programming language in the world as of January 2022. Modern languages such as Go, Swift, Scala, and Python are not as popular as C. Where is C used today?


2 Answers

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.

like image 127
Sergey Kalinichenko Avatar answered Sep 21 '22 12:09

Sergey Kalinichenko


Base64 encoding converts 3 octets into 4 encoded characters; therefore

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

Read here.

like image 36
Icarus Avatar answered Sep 21 '22 12:09

Icarus