Encode and decode Base64 via command line

0
8044
Encode and decode Base64 via command line
Encode and decode Base64 via command line

In this post, I will show you several ways to encode and decode base64 via command line, which works in every operating systems.

NOTE

In following command examples, I use raw.txt for raw input text, and encoded.txt for base64-encoded data.

Using base64 utility

base64 is a very handy command line utility which is available in Linux and MacOS.

For Windows, you can use this ported version.

To encode base64 for an input file, issue this command:

$ echo "123" > raw.txt

$ base64 raw.txt
MTIzCg==

By default, echo command will append a newline character to the output, you might want to omit it by using -n argument.

$ echo -n "123" > raw.txt

$ base64 raw.txt
MTIz

For some Linux distros, you might need to specify the input file by using -i, --input :

$ base64 -i raw.txt
MTIz

The encoded base64 value, by default, is printed on the stdout; if you want to save into an file, you can use either one of following commands:

$ base64 -i raw.txt -o encoded.txt

$ cat encoded.txt
MTIz

$ base64 -i raw.txt > encoded.txt

$ cat encoded.txt
MTIz

If you just want to quickly perform base64 encoding for a string and get the output, use any of these commands:

$ cat raw.txt | base64
MTIz

$ echo -n "123" | base64
MTIz

$ printf "123" | base64
MTIz

To decode base64-encoded data, use the -d argument:

$ echo "MTIz" | base64 -d
123

$ cat encoded.txt| base64 -d
123

Using openssl utility

You can also use openssl to perform base64 encoding and decoding, but it might require to install for the operating system.

openssl works with same way as base64 utility. These are some example commands:

$ openssl base64 -in raw.txt -output encoded.txt
MTIz

$ echo -n "123" | openssl base64
MTIz

$ openssl base64 -d -in encoded.txt -out raw.txt

$ openssl base64 -d -in encoded.txt

$ echo "MTIz" | openssl base64 -d

Conclusion

That’s it, now you know how to encode and decode base64 data from command line.

Have fun!