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?

Andrea Corbellini
  • 15,616
  • 2
  • 64
  • 81
Jarwin
  • 325
  • 1
  • 2
  • 9

1 Answers1

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.

A.B.
  • 89,123
  • 21
  • 245
  • 323
  • 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 05 '15 at 09: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. – Andrea Corbellini Nov 05 '15 at 10:00
  • @AndreaCorbellini Can I add your comment to the answer? – A.B. Nov 05 '15 at 10:08
  • 1
    Of course====== – Andrea Corbellini Nov 05 '15 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 05 '15 at 11:01