8

Is there a tool that will do this in bash?

leeand00
  • 4,443
  • 10
  • 51
  • 78

1 Answers1

11

Packages

Yes, there are several. The package coreutils (installed by default in debian) carry both base32 and base64. They could either encode or decode:

$ printf '%s' "abc" | base64
YWJj

$ printf '%s' "abc" | base64 | base64 -d
abc

Understand that using echo might add a trailing new line that will change the resulting base64 encoded string:

$ echo "abc" | base64
YWJjCg==

There are also other packages that have similar tools in packages basez and openssl. The latter is also usually installed by default, the former is not.

$ printf '%s' "abc" | openssl base64
YWJj

Encoding

That the source string is encoded in any locale (codepage) is irrelevant to base64 encoding. A base64 program encodes bytes, not characters.

$ printf '%s' "éäìǫ" | base64 | base64 -d
éäìǫ

Will work on any system exactly the same. Well, in any sane system in which echo "éäìǫ" will also print éäìǫ on the command line.

Of course, if the source string is encoded in one system and then decoded in a system with a different locale, it is quite probable that you will get a Mojibake string. That is not a problem to be solved by base64, it is an issue to be solved by changing the encoding of the string. Probably with iconv.

$ echo -n "Москва" | base64            # in a utf8 locale
0JzQvtGB0LrQstCw

However, in a Cyrillic locale with iso889-5 (maybe ru_RU.ISO-8859-5, there are other languages with Cyrillic):

$ echo "0JzQvtGB0LrQstCw" | base64 -d
ааОбаКаВаА

$ echo "0JzQvtGB0LrQstCw" | base64 -d | iconv -f utf8 -t iso8859-5
Москва
Cristian Ciupitu
  • 2,430
  • 1
  • 22
  • 29
  • 1
    why `printf '%s'` instead of `echo -n`? – qwr Jul 31 '21 at 07:27
  • 2
    @qwr `echo -n` is not portable. POSIX states the behaviour of `-n` is: "... implementation-defined". `printf '%s'` on the other hand has POSIX specified behaviour. – tsujp Jan 12 '23 at 09:08