How to Encode or Decode a base64 String on Linux
Base64 is a binary-to-text encoding scheme that is commonly used to encode binary data, especially when that data needs to be sent over media that are designed to handle text. T
This encoding process also helps us to ensure that the data remains intact without alteration during transport. On the other hand, decoding is the process of converting base64 encoded data back into its original binary format.
In this tutorial, we will explore the various tools and methods we can use to encode and decode base64 data in the Linux ecosystem
Method 1 - Using the Base64 Utility
The base64
utility is a command-line utility that can encode and decode base64 strings. It is typically pre-installed on most Linux distributions.
Encoding
To encode a string, you can echo the string and pipe it to the base64
command. For example:
echo -n 'Hello World' | base64
The -n
option tells echo
not to output the trailing newline.
The resulting string will be an base64 encoded string as:
SGVsbG8gV29ybGQ=
Decoding
To decode a base64 string, you use the -d
or --decode
option:
echo 'SGVsbG8gV29ybGQ=' | base64 --decode
The output will be the original string.
Hello World
Method 2 - Using the OpenSSL Utility
OpenSSL is a robust, full-featured open-source toolkit that implements the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.
It also includes a command-line utility that can be used for various purposes, including encoding and decoding base64 strings.
Encoding
To encode a string, you can echo the string and pipe it to the openssl base64
command:
echo -n 'Hello World' | openssl base64
The result:
SGVsbG8gV29ybGQ=
Decoding
To decode a string, you use the -d
or --decode
option:
echo 'SGVsbG8gV29ybGQ=' | openssl base64 -d
Output:
Hello World
Method 3: Using Python
We can also use Python encoding and decoding functionality to encode and decode base64 strings.
Encoding
Open a Python interactive shell by typing python
or python3
in your terminal.
Import the base64
module and use the b64encode
method to encode a string:
import base64
encoded = base64.b64encode(b'Hello World')
print(encoded)
The code above will return a byte string:
b'SGVsbG8gV29ybGQ='
Decoding
Use the b64decode
method to decode a base64 string:
import base64
decoded = base64.b64decode(b'SGVsbG8gV29ybGQ=')
print(decoded)
The result:
b'Hello World'
If you want to convert this byte string to a regular string, you can use the decode
method of the byte string:
print(decoded.decode('utf-8'))
This will output the string Hello World
.
Conclusion
In this tutorial, we covered how to encode and decode a base64 string on Linux using the base64
utility, the openssl
utility, and Python.