base64: Add no-LF variant for encoding

base64_encode_no_lf() is otherwise identical to base64_encode(), but it
does not add line-feeds to split the output.

Signed-off-by: Jouni Malinen <jouni@codeaurora.org>
This commit is contained in:
Jouni Malinen 2020-06-15 20:18:12 +03:00 committed by Jouni Malinen
parent 6dc2c0118a
commit c7e6dbdad8
2 changed files with 19 additions and 6 deletions

View file

@ -9,6 +9,7 @@
#include "includes.h"
#include <stdint.h>
#include "utils/common.h"
#include "os.h"
#include "base64.h"
@ -18,6 +19,10 @@ static const char base64_url_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
#define BASE64_PAD BIT(0)
#define BASE64_LF BIT(1)
static char * base64_gen_encode(const unsigned char *src, size_t len,
size_t *out_len, const char *table, int add_pad)
{
@ -29,7 +34,7 @@ static char * base64_gen_encode(const unsigned char *src, size_t len,
if (len >= SIZE_MAX / 4)
return NULL;
olen = len * 4 / 3 + 4; /* 3-byte blocks to 4-byte */
if (add_pad)
if (add_pad & BASE64_LF)
olen += olen / 72; /* line feeds */
olen++; /* nul termination */
if (olen < len)
@ -49,7 +54,7 @@ static char * base64_gen_encode(const unsigned char *src, size_t len,
*pos++ = table[in[2] & 0x3f];
in += 3;
line_len += 4;
if (add_pad && line_len >= 72) {
if ((add_pad & BASE64_LF) && line_len >= 72) {
*pos++ = '\n';
line_len = 0;
}
@ -59,19 +64,19 @@ static char * base64_gen_encode(const unsigned char *src, size_t len,
*pos++ = table[(in[0] >> 2) & 0x3f];
if (end - in == 1) {
*pos++ = table[((in[0] & 0x03) << 4) & 0x3f];
if (add_pad)
if (add_pad & BASE64_PAD)
*pos++ = '=';
} else {
*pos++ = table[(((in[0] & 0x03) << 4) |
(in[1] >> 4)) & 0x3f];
*pos++ = table[((in[1] & 0x0f) << 2) & 0x3f];
}
if (add_pad)
if (add_pad & BASE64_PAD)
*pos++ = '=';
line_len += 4;
}
if (add_pad && line_len)
if ((add_pad & BASE64_LF) && line_len)
*pos++ = '\n';
*pos = '\0';
@ -164,7 +169,14 @@ static unsigned char * base64_gen_decode(const char *src, size_t len,
*/
char * base64_encode(const void *src, size_t len, size_t *out_len)
{
return base64_gen_encode(src, len, out_len, base64_table, 1);
return base64_gen_encode(src, len, out_len, base64_table,
BASE64_PAD | BASE64_LF);
}
char * base64_encode_no_lf(const void *src, size_t len, size_t *out_len)
{
return base64_gen_encode(src, len, out_len, base64_table, BASE64_PAD);
}

View file

@ -10,6 +10,7 @@
#define BASE64_H
char * base64_encode(const void *src, size_t len, size_t *out_len);
char * base64_encode_no_lf(const void *src, size_t len, size_t *out_len);
unsigned char * base64_decode(const char *src, size_t len, size_t *out_len);
char * base64_url_encode(const void *src, size_t len, size_t *out_len);
unsigned char * base64_url_decode(const char *src, size_t len, size_t *out_len);