1

I am trying to make a bash script work on MinGW and it seems the shell is not able to decode something like the following.

t=$(openssl rand -base64 64)
echo "$t" | base64 --decode

Resulting in,

 Ԋ7▒%
     ▒7▒SUfX▒L:o<x▒▒䈏ţ94V▒▒▒▒uW;▒▒pxu▒base64: invalid input

Interestingly, if I output the base64 character and run the command as such, it works.

echo "+e5dcWsijZ83uR2cuKxIDJTTiwTvqB7J0EJ63paJdzGomQxw9BhfPvFTkdKP9I1o
g29pZKjUfDO8/SUNt+idWQ==" | base64 --decode

Anybody knows what I am doing wrong?

Thanks

Starx
  • 77,474
  • 47
  • 185
  • 261

2 Answers2

0

I solved the above case by passing --ignore-garbage flag to the base64 decode. It ignores the non-alphabet characters.

echo "$t" | base64 --decode --ignore-garbage

However, I would still like to know how did I create "garbage" ;) ?

Starx
  • 77,474
  • 47
  • 185
  • 261
0

I think what has happened here is the base64 string contains some embedded spaces, and that causes the actual "invalid input" w (and what you observe to as garbage.)

The openssl rand -base64 64 command introduces some newlines (not spaces), for example,

openssl rand -base64 64 > b64.txt

... then viewing the b64.txt file in an editor I see two separate lines

tPKqKPbH5LkGu13KR6zDdJOBpUGD4pAqS6wKGS32EOyJaK0AmTG4da3fDuOI4T+k
abInqlQcH5k7k9ZVEzv8FA==

... and this implies there is a newline character between the 'k' and 'a'

So the base64 string has this embedded newline. The base64 -d can handle newlines (as demonstrated by your successful example), but, it cannot handle space char.

The newlines can get translated to spaces by some actions of the shell. This is very likely happening by the echo $t I.e. if t has newlines inside it, then echo will just replace then with single space. Actually, how it behaves can depend on shell options, and type of string quotes, if any, applied.

To fix the command, we can remove the newline before piping to the base64 -d command.

One way to do that is to use tr command, e.g. the following works on Linux:

t=$(openssl rand -base64 64 | tr -d '\n')
echo $t | base64 -d

... or alternatively, remove the spaces, again using tr

t=$(openssl rand -base64 64)
echo $t | tr -d ' ' | base64 -d
Darren Smith
  • 2,261
  • 16
  • 16