Want to learn how to encode and decode strings using the base64 binary-to-text scheme? This tutorial will show you two methods to encode and decode a string on Linux using the base64 command and the Python programming language.



Where Is base64 Used?

base64 is widely used in different domains. Some of the most common areas include email attachments, web development, networking, and URL encoding.

Some email systems use base64 to encode binary data such as images and documents into text format so that these can be safely transmitted with the message. Web developers also use base64 to embed images into HTML and CSS to reduce the number of HTTP requests and improve page load speed.

Another common use of base64 encoding is in authentication tokens. Usernames and passwords are sometimes masked using this encoding scheme and added to HTTP headers or URL parameters. In networking, base64 is used in protocols that use text-based communication, such as HTTP and SMTP, for transmitting data without corruption.

What you should know is that base64 is only an encoding scheme. The encoded data can be easily decoded to get the original data back. You should never use it if you need to encrypt data instead.

Encoding a String Using the base64 Command

The most basic way to encode a string using base64 is to output it to the terminal using the echo command. The trick is to pipe the output of the echo command to base64, like this:

echo 'I love Linux' | base64

The Linux terminal showing the process of encoding a string

Because of the default behavior of the echo command, there’s a trailing newline character at the end of the string. If you’d like to omit that and only use the string, run:

echo -n 'I love Linux' | base64

The Linux terminal displaying the process of encoding a string using base64 omitting the newline character

As you can notice, the output is different from the previous one. You can also do this using the printf command which doesn’t automatically append a newline character to the string. The format is given below:

printf 'I love Linux' | base64

The Linux terminal showing the process of encoding a string received from the printf command using base64

This output is the same as the previous one because there are no newline characters this time. If you’re familiar with here-strings on Linux, you can also use them to send your string output to the base64 command like this:

base64 <<< 'I love Linux'

The Linux terminal showcases how to encode a string using the base64 command with the help of here string operator

Similar to the echo command, here-strings also add a newline character at the end of the string.

Encoding Files Using the base64 Command

To encode a file using base64, you can pass the file directly as an option to the base64 command.

To test it out, create a new file and append some text to it. If you already have a text file, then use that. I’ve created a file called base.txt. To encode the file’s content to base64, run:

base64 base.txt

The Linux terminal displaying the process of encoding a file to base64 using the base64 command

Remember to replace base.txt with your file name. The above command only displays the output in the terminal. It doesn’t save the encoded string anywhere. However, you can easily do that by redirecting the output to a new file. I’ve created another file called output.txt. This time I’ll save the output to that empty file. Here’s the command for that:

base64 base.txt > output.txt

The Linux terminal showcasing the process of encoding the content of a file to base64 and saving it to another file

As you can see, the terminal didn’t display the output. This command saved it to another file instead.

Decoding a base64 String Using the base64 Command

For decoding a base64 string and turning it into a regular string, you’ll need to use the “-d” flag with the base64 command. Let’s see a demonstration using the echo command.

echo 'SG93VG9HZWVrCg==' | base64 -d

The Linux terminal displaying the process of decoding a base64 string using the base64 command with the help of the echo command

If you’d like to use here-strings for decoding a base64 string, then use:

base64 -d <<< SG93VG9HZWVrCg==

The Linux terminal displaying the process of decoding a base64 string using the base64 command with the help of here-strings

Sometimes, there might be non-alphanumeric characters in a string. You can ignore those while decoding the string by using the “-i” option.

Using Python to Encode and Decode a base64 String

If you’re a Python programmer or are more familiar with the Python programming language than Bash, then this method will be more suitable for you. Python has a base64 module that you can use for encoding and decoding strings. You can either use the python3 terminal command or write a full program. I’ll show you both ways.

The python3 command has a “-m” or module flag. You can use this flag to invoke the base64 module. Then you can pass your string with the help of the echo command or here-strings. Here’s the full command:

echo 'I love Linux' | python3 -m base64 # Using the echo commandpython3 -m base64 <<< 'I love Linux' # Using here-strings

The Linux terminal displays the process of encoding a string to base64 using Python language

To decode a base64 string, all you need to do is use the “-d” flag as seen previously with the base64 command. The syntax is below:

echo 'SSBsb3ZlIExpbnV4Cg==' | python3 -m base64 -d # Using the echo command​​​​​​python3 -m base64 -d <<< 'SSBsb3ZlIExpbnV4Cg==' # Using here-strings

The Linux terminal showing the process of decoding a base64 string using the Python language

Of course, the convenient way is to create a Python program that can handle the encoding and decoding by taking user input. First, let’s create a program that will encode a string. Here’s the encoding code:

 import base64
input_string = input("Enter the string to encode: ")
encoded_string = base64.b64encode(input_string.encode('utf-8'))
decoded_string = base64.b64decode(encoded_string).decode('utf-8')
print("Encoded string:", encoded_string.decode('utf-8'))
print("Decoded string (verification):", decoded_string)

Save the file with a suitable name and a “.py” extension. I’m saving it by the name base64_encoder.py. Once done, run the program with:

python3 base64_encoder.py

The Linux terminal showcasing the process of encoding a string using a Python program

You can also create a program to decode a base64 string. Here’s a code snippet you can use:

 import base64
encoded_string = input("Enter the Base64 string to decode: ")
try:
   
   decoded_string = base64.b64decode(encoded_string).decode('utf-8')
   print("Decoded string:", decoded_string)
except Exception as e:
   print(f"Error decoding string: {e}")

Save the file and run the program in the same way.

python3 base64_decoder.py

The Linux terminal displaying the process of decoding a base64 string using a Python program

Now you can use these Python programs to encode and decode any strings.


So these are two of the easiest ways to encode and decode strings using base64. If you’d like to learn more about the base64 command on Linux, it’s better to check out its manual page.

Source link