firmware-development-blog-articles

Base64 Encoding and Decoding on ESP32

by Pratik (PCBArtist)

The ESP-IDF contains functions for enabling Base64 encoding and decoding on ESP32. The encoding and decoding functions are actually built into the ESP32 ROM. The functions are accessible by using header files for mbedTLS base64 encoding and decoding.

Base64 related header file

To use base64 encoding and decoding on ESP32, you can include this header file.

#include "mbedtls/base64.h" 

Base64 encoding

Here is a snippet that lets you convert a string to base64.

unsigned char *input = "ABCD123";
unsigned char output[64];
size_t outlen;

mbedtls_base64_encode(output, 64, &outlen, input, strlen(input)); 

The array output contains the base64 encoded text.
The input string is converted and the length of output string length is stored in outlen.

You have to make sure that the output buffer is large enough.

Base64 decoding

Here is a snippet for decoding base64 strings to plaintext.

unsigned char *input = "QUEtQkItQ0MtREQtRUUtRkY6MDAwMA==";
unsigned char output[64];
size_t outlen;

mbedtls_base64_decode(output, 64, &outlen, input, strlen(input)); 

The array output contains the plain text output.
The input base64 encoded string is converted and the length of output string length is stored in outlen.

Again, ensure that your output buffer is large enough.

You may also like

Have something to add?