17

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?

1
  • 3
    Hint: what's the difference between base64 -d <<< MTIzNDU2Nzg5 and base64 -d <<< MTIzNDU2Nzg5Cg==? Nov 5, 2015 at 9:44

1 Answer 1

40

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.

5
  • Okay, that makes sense. But when I did echo | base64 I got Cg== as a result, but in echo qwertyuiop | base64 is it o=? I got it that why was that happening, but I am still having a hard time understanding how this is happening.?
    – Jarwin
    Nov 5, 2015 at 9:50
  • 8
    @Jarwin: 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. Nov 5, 2015 at 10:00
  • @AndreaCorbellini Can I add your comment to the answer?
    – A.B.
    Nov 5, 2015 at 10:08
  • 1
    Of course====== Nov 5, 2015 at 10:12
  • 1
    If the answer is clear, you should accept by a click on the check mark at the left side of the answer.
    – A.B.
    Nov 5, 2015 at 11:01

Not the answer you're looking for? Browse other questions tagged .