Base64 Encoding Implementation in Rust

yamaguchi naoto
2 min readFeb 2, 2022
Photo by Yu Kato on Unsplash

Introduction

Recently, it’s fun for me to write in Rust. But soon i forget Rust syntax, because my current job use not Rust but Go. So I’ m going to use Rust to implement Base64.

What’s Base64

Base64 ,defined in RFC4648, is encoding format. It’s feature is that encoding data is generated by 64 char of ASCII for binary data or multi byte data.

I often use it, when i want to pass the struct to URL query parameter. (ex: struct A -> proto.Marshal() -> base64)

Theory

  1. Input value is converted to binary values.
  2. binary value is split by each 6 bit.
  3. If last value is shorter than 6 bit, last value filled 0 .
  4. 6 bits is converted every 4 char (24 bit) from Base64 Table.
  5. if converted string short 24 bit, last encoding block added padding char (=).

Let’s Implementation

1. Converting to Binary

First, convert input to binary.

2. Splitting to every 6 bit

Next, split binary to every 6 bit.

3 If necessary, adding 0

If last value is shorter than 6 bit, last value filled 0 . ex) 1111 -> 111100

4. Converting from base64 table

To convert bits to char, create HashMap(base64 table) from JSON file using serde_json . And converting by HashMap.

Following sample Base64 Table.

https://en.wikipedia.org/wiki/Base64#Base64_table

5 If necessary, adding =

if last block char is shorter than 4, it fill padding char.

At last, base64 encoding is finished.

$ cargo run
> input: "naoto"
> bmFvdG8=
$ echo -n 'naoto' | base64
> bmFvdG8=

Conclusion

I tried to implement base64 encoding by Rust. In this article, this base64 implementing is verbose and easy to understand.

I guess that actual implementation is used by shift operator, but I’ve enjoyed to know Base64 encoding theory.

  • full source code link

naoto0822/a61ef5a0a2c3d1dc1b23166f4954538c

References

--

--