de en

Thorsten Reimers

Use Base64 Encoding for Basic Auth correctly

May 29, 2024

In order to convert user id and a password into a Base64 string the Linux-Tool base64 can be used.

Many instructions recommend the following

$ echo "user:password" | base64 
dXNlcjpwYXNzd29yZAo=

Be noted that this is error prone. echo adds a line break which is coded into the resulting base64 string.

Even if converting back the problem is not obvious:

$ echo "dXNlcjpwYXNzd29yZAo=" | base64 -d
user:password

Taking a closer look shows the wrong line break at the end:

$ echo "dXNlcjpwYXNzd29yZAo=" | base64 -d | hexdump -C
00000000  75 73 65 72 3a 70 61 73  73 77 6f 72 64 0a        |user:password.|
0000000e

Suppress the line break to encode the input correctly:

$ echo -n "user:password" | base64 
dXNlcjpwYXNzd29yZA==

Now decoding back does not show any unintended line breaks:

$ echo "dXNlcjpwYXNzd29yZA==" | base64 -d
user:password$

The bash prompt must appear directly after the output!