Rust: Encoding and Decoding Base64 Strings using the Windows API

Pratik Chowdhury
3 min readFeb 13, 2022

DISCLAIMER

  1. Windows Only
    No Linux/macOS support

DEPENDENCY

In this project, we will use Windows-RS to access Rust APIs.

Traditionally using the following would be enough

However, when using Windows Rust bindings, all interesting things are hidden behind optional features.
The features of interest can be found from the docs for functions that we will use.

As we can see, the features of interest are Security Cryptography and Storage Streams

Imp. Functions

  1. EncodeToBase64String
    Returns Buffer as Output
  2. DecodeFromBase64String
    Takes Buffer as input

Buffer to String conversion

  1. EncodeToBase64String returns IBuffer as output.
  2. However, in Rust a user would expect to use a String.
  3. So we need to convert IBuffer to String.

Conversion

  1. Read Buffer using DataReader
  2. Allocate a Vector of buffer length size
  3. Read from the DataReader into the Vector
  4. Convert the Vector to String

First attempt

As you can see the function is simple and it works.

However, best of Rust users are going to be aware that unwrap while very convenient is not the safest of ways.
One way to solve this easily could be by using from_utf8_unchecked but the function is unsafe

let string = unsafe { String::from_utf8_unchecked(temp) };

Arguably the better and safer way would be to map the FromUTF8 Error to a windows::core::Error

As you can see, we will have to use one of the Windows Error Codes here. To use the error code E_FAIL, we will need to add the feature Win32_Foundation.

Encoding a String to Base64

  1. Take input as String
  2. Read String into Buffer
  3. Call Encode function which returns HSTRING
  4. Convert HSTRING to String and return

Decoding a Base64 to a String

  1. Convert String to HSTRING
  2. Call Decode function which returns IBuffer
  3. You remember stringify_buffer?
    No? Because we use that to convert Buffer to String

Verifying it works

Let’s run a simple unit test to verify

Result

Yeah it works with emojis.

And meme making apparently

FULL Code

The repo is here

Cross platform base64

There probably are many libraries for his. I found one by the name of base64. It is documented.

Source code from their README. Much shorter.

My own library

And that is why to simplify it all, I decided to write my own library, win-base64.
I have intentionally written the sample code to be similar to the base64 one.

You can always use this if you decide adding the above solution to your own project is far too verbose.

Dependency management

Contact me!

You can comment here or contact me via LinkedIn.

--

--