From 48c33ae0a208e6b637475ec8c68fe0e5e0741f10 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Tue, 15 Dec 2020 12:18:45 +0100 Subject: [PATCH] sys/base64: drop padding for base64url encoding 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. --- sys/base64/base64.c | 15 +++++++++++++-- tests/unittests/tests-base64/tests-base64.c | 4 ++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/sys/base64/base64.c b/sys/base64/base64.c index 1e885cc5f2..4e7b565606 100644 --- a/sys/base64/base64.c +++ b/sys/base64/base64.c @@ -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; @@ -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; } diff --git a/tests/unittests/tests-base64/tests-base64.c b/tests/unittests/tests-base64/tests-base64.c index 573686d4d0..80a5403907 100644 --- a/tests/unittests/tests-base64/tests-base64.c +++ b/tests/unittests/tests-base64/tests-base64.c @@ -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)]; @@ -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);