base64 encode is giving ambigious results [duplicate]

I was encoding (from terminal) into base64. But I guess the commands are not executing properly.

$ echo 123456789 | base64
MTIzNDU2Nzg5Cg==

And then when I did the same on base64encode, I got this result

MTIzNDU2Nzg5

I thought that maybe echo is being encoded as well so i ran

$ echo | base64
Cg==

I guess i was right, but that didn't help either as in another instance:

$ echo qwertyuiop | base64
cXdlcnR5dWlvcAo=

and when the same was encoded using base64encode the result was

cXdlcnR5dWlvcA==

And not suprisingly i the results from base64encode were accepted(in SMTP)

So, what am i missing here? and how can i sucessfully convert the string or number into base64?


Solution 1:

The answer is simple. With

echo 123456789 | base64

or

echo qwertyuiop | base64

you always have a trailing newline.


Avoid this behavior by using the n switch for the echo command

% echo -n qwertyuiop | base64
cXdlcnR5dWlvcA==

or use printf

% printf qwertyuiop | base64
cXdlcnR5dWlvcA==

as you can see it is the same result as returned by base64encode.


And as @AndreaCorbellini says in the comments

Base64 produces 4 bytes of output for every 3 bytes of input, so there is never a 1:1 corrispondence between the input bytes and the output bytes. This means that a new line may end up being encoded in different ways, depending on the bytes that precede and follow it.