Skip to content

Commit

Permalink
sys/base64: drop padding for base64url encoding
Browse files Browse the repository at this point in the history
The URLsafe base64 encoding variant does not require padding, using
'=' as padding is in fact an error as it is not a URL-safe character.
  • Loading branch information
benpicco committed Dec 15, 2020
1 parent 41a844f commit 48c33ae
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 13 additions & 2 deletions sys/base64/base64.c
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ static int base64_encode_base(const void *data_in, size_t data_in_size,
void *base64_out, size_t *base64_out_size,
bool urlsafe)
{
const uint8_t padding = urlsafe ? 0 : '=';
const uint8_t *in = data_in;
const uint8_t *end = in + data_in_size;
uint8_t *out = base64_out;
Expand Down Expand Up @@ -131,14 +132,24 @@ static int base64_encode_base(const void *data_in, size_t data_in_size,
encode_three_bytes(out, in[0], 0, 0, urlsafe);
/* Replace last two bytes with "=" to signal corresponding input bytes
* didn't exist */
out[2] = out[3] = '=';
out[2] = out[3] = padding;

/* padding is not required for urlsafe application */
if (urlsafe) {
*base64_out_size -= 2;
}
return BASE64_SUCCESS;
}

/* Final case: 2 bytes remain for encoding, use zero as third input */
encode_three_bytes(out, in[0], in[1], 0, urlsafe);
/* Replace last output with "=" to signal corresponding input byte didn't exit */
out[3] = '=';
out[3] = padding;

/* padding is not required for urlsafe application */
if (urlsafe) {
*base64_out_size -= 1;
}

return BASE64_SUCCESS;
}
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/tests-base64/tests-base64.c
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ static void test_base64_10_decode_empty(void)
static void test_base64_11_urlsafe_encode_int(void)
{
uint32_t data_in = 4345;
unsigned char expected_encoding[] = "-RAAAA==";
unsigned char expected_encoding[] = "-RAAAA";

size_t base64_out_size = 0;
char base64_out[sizeof(expected_encoding)];
Expand Down Expand Up @@ -448,7 +448,7 @@ static void test_base64_11_urlsafe_encode_int(void)

static void test_base64_12_urlsafe_decode_int(void)
{
static const char encoded_base64[] = "_____wAA==";
static const char encoded_base64[] = "_____wAA";
static const uint8_t expected[] = {0xFF, 0xFF, 0xFF, 0xFF, 0x0, 0x0};

size_t base64_size = strlen(encoded_base64);
Expand Down

0 comments on commit 48c33ae

Please sign in to comment.