Skip to content

Instantly share code, notes, and snippets.

@VNovytskyi
Created March 12, 2022 10:28
Show Gist options
  • Save VNovytskyi/dd4078095e15ab9e1ee6b4761754c84c to your computer and use it in GitHub Desktop.
Save VNovytskyi/dd4078095e15ab9e1ee6b4761754c84c to your computer and use it in GitHub Desktop.
Arduino ESP32 Base64 decoding with MBedTLS
#include "mbedtls/base64.h"
#include "mbedtls/error.h"
size_t get_decoded_size(const char *base64_str_p) {
if (base64_str_p == NULL) {
return 0;
}
size_t pad_char_count = 0;
size_t base64_str_len = strlen(base64_str_p);
if ((base64_str_len < 4) || (base64_str_len % 4 != 0)) {
return 0;
}
if (base64_str_p[base64_str_len - 1] == '=') {
pad_char_count++;
}
if (base64_str_p[base64_str_len - 2] == '=') {
pad_char_count++;
}
return (3 * (base64_str_len / 4)) - pad_char_count;
}
void setup() {
const char *data_base64 = "RrDWIKA8fN1zroSWUaSLykGlLI3OeVSNkEz1HaUW5WcbUKCGxCOHZk9EEgGshY0ovbuRlnEPWE+WLZDVCq4k9b+ylckgvOx/PpiawezezdE6BgPjibaLRQ/PPnaMk+IuvTerX/f0ulICQWWZWIffA6GvYfrdjBk74cGwj+pIG3k=";
size_t decoded_data_size = get_decoded_size(data_base64);
uint8_t *decoded_data_buff = (uint8_t*)malloc(decoded_data_size);
if (decoded_data_buff == NULL) {
printf("Fail to allocate %zu bytes...\n", decoded_data_size);
return;
}
size_t decoded_data_length = 0;
int res = mbedtls_base64_decode(
decoded_data_buff,
decoded_data_size,
&decoded_data_length,
(const uint8_t*)data_base64,
strlen(data_base64)
);
if (res != 0) {
char err_buff_str[128];
mbedtls_strerror(res, err_buff_str, sizeof(err_buff_str));
printf("Failed decode data, error: %s\n", err_buff_str);
free(decoded_data_buff);
return;
}
printf("Data [%zu]: ", decoded_data_length);
for (size_t i = 0; i < decoded_data_length; ++i) {
printf("%02X ", decoded_data_buff[i]);
}
printf("\n");
free(decoded_data_buff);
}
void loop() {
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment