Search code examples
base64passwords

Do I need to include -n option when encoding a password using base64?


I read somewhere that when encoding a password in base64, I should use echo -n to prevent the newline from being included in the encoded value. For example,

echo changeme | base64
Y2hhbmdlbWUK
echo -n changeme | base64
Y2hhbmdlbWU=

These two base64 strings are different, but when I decode them they are the same

echo Y2hhbmdlbWUK | base64 -d
changeme
echo Y2hhbmdlbWU= | base64 -d
changeme

So do I really need to add the -n option https://linux.die.net/man/1/echo says:

do not output the trailing newline

Searches gave this long winded example using python... didn't read it all Simple way to encode a string according to a password?


Solution

  • When you use an online converter to decode it to hex, you'll see that the first string becomes 6368616e67656d650a and has 0a (ASCII Linefeed) on the end, which the second doesn't have.

    So the answer is yes, you really need to add the -n option.

    If you change your echo to echo -n you'll see this as well.

    echo -n Y2hhbmdlbWU= | base64 -d
    changemePROMPT-SHOWS-HERE
    

    Another way to see this is using the following UNIX command:

    echo -n Y2hhbmdlbWUK | base64 -d | od -c
    0000000   c   h   a   n   g   e   m   e  \n
    
    echo -n Y2hhbmdlbWU= | base64 -d | od -c
    0000000   c   h   a   n   g   e   m   e
    

    Where you can see the first encoding includes the linefeed and the second does not.