How to Base64 Encode a String in Terminal
Shannon Crabill
Posted on December 14, 2020
While browsing some API documentation, I saw references to Base64 for passing credentials to the API. I had seen Base64 referenced a few times, but had no idea how to convert text into Base64.
So, I did some digging.
This post will outline how to encode (and decode) text into Base64 using the MacOS Terminal.
What is Base64?
I should share a little bit about what Base64 is. The MDN documentation explains the overarching concept of Base64 as.
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.
You can think of Base64 is another way to represent binary or text data.
The conversion process is somewhat detailed, and I encourage you to check out the resources at the bottom of this article if you are curious about the benefits and technical details of Base64.
Converting Text into Base64
While reading those API docs, I had no idea how to create a Base64 string.
There are converters a few Google searches away. But, did you know there’s a Base64 command built into the MacOS?
To turn a string into Base64, open a new Terminal window, and use this format.
base64 <<< string
That would be base64
followed by a space, three less-than signs (<
), another space, then whatever string
you want to encode in Base64.
Here’s an example:
If I wanted to convert the string I love cheeseburgers
into Base64, I would enter this:
base64 <<< "I love cheeseburgers"
Which would print out SSBsb3ZlIGNoZWVzZWJ1cmdlcnMK
as a result.
Note: You only need quote marks around the string you would like to convert if it has space it in.
The following does not need quote marks, for example:
base64 <<< ilovecheeseburgers
If you're curious, base64 <<< ilovecheeseburgers
returns aWxvdmVjaGVlc2VidXJnZXJzCg==
which is very different from what base64 <<< "I love cheeseburgers"
returns.
Decoding Base64
With a similar command, you can decode Base64 back into human, readable text.
Let’s say a friend of ours sent us the following code:
SSBsb3ZlIHlvdSBtb3JlCg==
To decode Base64, we add a -D
flag before the three arrows and after base64
.
Like this:
base64 -D <<< SSBsb3ZlIHlvdSBtb3JlCg==
Which returns I love you more
. How sweet!
Base64 is Not Unique
While a Base64 string like SSBsb3ZlIGNoZWVzZWJ1cmdlcnMk
looks random, it is not.
Each time I run base64 <<< "I love cheeseburgers"
it’ll return the same result. If you run the same code, you’ll get the same result. And since a Base64 string can be decoded, it’s not appropriate for hashing passwords, storing API keys, etc.
Resources
The post Base64 Encoding appeared first on Shannon Crabill — Front End Software Engineer.
Posted on December 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 25, 2023