How text becomes Base64, step by step
Take the text Hi!. In UTF-8 its three characters are the bytes 48 69 21, which are 01001000 01101001 00100001 in binary. Base64 regroups those 24 bits into four groups of 6 bits: 010010 000110 100100 100001. Each group is a number from 0 to 63, which picks a character from the Base64 alphabet: 18 is S, 6 is G, 36 is k and 33 is h. The result is SGkh.
When the text is not a multiple of 3 bytes long, the last group is short and the output is padded with =. Hi becomes SGk=, and H becomes SA==.
Why two tools can give different results for the same text
If two Base64 strings differ, one of these is almost always the reason:
- A newline was included. On the command line,
echo "hello" | base64encodes the newline thatechoadds. Useecho -norprintfto leave it out. - A different text encoding. UTF-8, UTF-16 and Latin-1 turn the same text into different bytes. Only plain ASCII text gives the same bytes in UTF-8 and Latin-1.
- A different alphabet or padding. URL-safe output uses
-and_, and some tools drop the=characters. - Line breaks. Some tools wrap the output every 76 characters, as email does. Others write one long line.
The options here let you reproduce each of those, so you can match the tool or library you need to be compatible with.
Encoding for PowerShell and for URLs
PowerShell's -EncodedCommand expects the command as Base64 of UTF-16 little endian text. Choose that text encoding and leave the other options at their defaults.
For a value that will sit inside a URL, such as a token in a query string, switch on the URL-safe alphabet and usually switch off the padding, so no character needs percent-encoding. To encode a whole URL instead, use the URL encoder.