Skip to content

Commit

Permalink
fixed base64 encoding not working for < 3 bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
RaphGL committed Oct 28, 2024
1 parent a4b75f5 commit 88fe8aa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 27 deletions.
3 changes: 2 additions & 1 deletion base64/base64.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ static const uint8_t base64_decode_map[] = {
// todo: fix encoding for strings with length < 3
const char *const base64_encode(const uint8_t *const data, size_t data_size) {
const size_t remaining = data_size % 3;
const size_t base64_len = ceil(((double)data_size * 8) / 6) + 1;
const size_t base64_len =
((double)data_size * 8) / 6 + 4 /* maximum padding + null char */;
char *result = malloc(base64_len);
if (!result) {
return NULL;
Expand Down
46 changes: 20 additions & 26 deletions base64/maintest.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,35 @@
#include <string.h>

int main(void) {
const char *decodee = "light w";
const char *decodee = "this is some long sentence to be encoded in base64.";
char *encoded = (char *)base64_encode((uint8_t *)decodee, strlen(decodee));
char *decoded = (char *)base64_decode(encoded, strlen(encoded));
assert(strcmp(decodee, decoded) == 0);

free((void *)encoded);
free((void *)decoded);

// -------

encoded = (char *)base64_encode((uint8_t *)"Man", 3);
assert(strcmp(encoded, "TWFu") == 0);
decoded = (char *)base64_decode(encoded, strlen(encoded));
assert(strcmp(decoded, "Man") == 0);
free((void *)encoded);
free((void *)decoded);

// ------

encoded = (char *)base64_encode((uint8_t *)"light work.", 11);
assert(strcmp(encoded, "bGlnaHQgd29yay4=") == 0);
decoded = (char *)base64_decode(encoded, strlen(encoded));
assert(strcmp(decoded, "light work.") == 0);
free((void *)encoded);
free((void *)decoded);

// ------

// todo: still crashing atm as function fails for args with len < 3
// encoded = (char *)base64_encode((uint8_t *)"ma", 2);
// assert(strcmp(encoded, "TWE=") == 0);
// decoded = (char *)base64_decode(encoded, strlen(encoded));
// assert(strcmp(decoded, "TWE=") == 0);
// free((void *)encoded);
// free((void *)decoded);
struct {
char *encoded;
char *decoded;
} res[] = {
{.decoded = "Man", .encoded = "TWFu"},
{.decoded = "light work.", .encoded = "bGlnaHQgd29yay4="},
{.decoded = "ma", .encoded = "bWE="},
};

for (size_t i = 0; i < sizeof(res) / sizeof(res[0]); i++) {
encoded = (char *)base64_encode((uint8_t *)res[i].decoded,
strlen(res[i].decoded));
assert(strcmp(encoded, res[i].encoded) == 0);
decoded = (char *)base64_decode(encoded, strlen(encoded));
assert(strcmp(decoded, res[i].decoded) == 0);

free(encoded);
free(decoded);
}

puts("tests passed.");
return 0;
Expand Down

0 comments on commit 88fe8aa

Please sign in to comment.