Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a base64 encoded string have an = sign at the end

I know what base64 encoding is and how to calculate base64 encoding in C#, however I have seen several times that when I convert a string into base64, there is an = at the end.

A few questions came up:

  1. Does a base64 string always end with =?
  2. Why does an = get appended at the end?
like image 308
santosh singh Avatar asked Aug 02 '11 18:08

santosh singh


1 Answers

Q Does a base64 string always end with =?

A: No. (the word usb is base64 encoded into dXNi)

Q Why does an = get appended at the end?

A: As a short answer: The last character ("=" sign) is added only as a complement(padding) in the final process of encoding a message with a special number of characters.

You will not have a '=' sign if your string has a multiple of 3 characters number, because Base64 encoding takes each three bytes (a character=1 byte) and represents them as four printable characters in the ASCII standard.

Example:

(a) If you want to encode

ABCDEFG <=> [ABC] [DEF] [G

Base64 will deal with the first block (producing 4 characters) and the second (as they are complete). But for the third, it will add a double == in the output in order to complete the 4 needed characters. Thus, the result will be QUJD REVG Rw== (without spaces).

[ABC] => QUJD

[DEF] => REVG

[G] => Rw==

(b) If you want to encode ABCDEFGH <=> [ABC] [DEF] [GH

similarly, it will add just a single = in the end of the output to get 4 characters.

The result will be QUJD REVG R0g= (without spaces).

[ABC] => QUJD

[DEF] => REVG

[GH] => R0g=

like image 57
Badr Bellaj Avatar answered Jan 04 '23 00:01

Badr Bellaj