all about that Base64
Today I spent some time pairing with a colleague, and needed to build a signature for an API call they needed to make, so I took to the googles and learned a bit about how Ruby deals with Base64.
If you’ve never heard of Base64, it’s a numeral system, or BASE-ically a standard for counting.
We’re most familiar with Base10 i.e. counting to 10 then starting over 0123456789
, or Base2 i.e. the Binary system that computers use 01
.
Base64 uses uppercase letters, lowercase letters, numbers, AND a few symbols to get the job done!
In ruby, you can use the Module Base64 to encode or decode things! Here’s an example:
# First, the Base64 Module isn't in Core ruby, so you have to require it
require "base64"
=> true
# you can use the method #encode64 and give an argument, and see it translated to Base64!
enc = Base64.encode64("kara is awesome")
=> "a2FyYSBpcyBhd2Vzb21l\n"
# you can even be super sleuth and double encode it! (
double_enc = Base64.encode64(enc)
=> "YTJGeVlTQnBjeUJoZDJWemIyMWwK\n"
# Then to revert back to your original messages, you use the method #decode64
revert = Base64.decode64(double_enc)
=> "a2FyYSBpcyBhd2Vzb21l\n"
plain = Base64.decode64(revert)
=> "kara is awesome"
Sandbox!
Resources
- Ruby Module Base64
- Wiki page for Base64
- Basecs Post on encodingHexes and Other Magical Numbers
- BaseCS PodcastS1 Ep2- What is Encoding?