libutil

C Utility Library
git clone http://git.omkov.net/libutil
Log | Tree | Refs | README | LICENCE | Download

libutil/src/base64.c (89 lines, 2.4 KiB) -rw-r--r-- blame download

012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
// util/base64.c, version 1.1.5
// Base64 source file from libutil
// Copyright (C) 2021, Jakob Wakeling
// MIT Licence

#include "base64.h"

#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static const uint8_t B64E[];
static const uint8_t B64D[];

/* Encode Base64 */
size_t b64encode(uint8_t *dst, uint8_t *src, size_t len) {
	register uint8_t *i = src, *o = dst;
	
	for (; len >= 3; len -= 3) {
		*o++ = B64E[i[0] >> 2];
		*o++ = B64E[((i[0] & 0x03) << 4) | (i[1] >> 4)];
		*o++ = B64E[((i[1] & 0x0F) << 2) | (i[2] >> 6)];
		*o++ = B64E[i[2] & 0x3F]; i += 3;
	}
	
	switch (len) {
	case 1: {
		*o++ = B64E[i[0] >> 2];
		*o++ = B64E[(i[0] & 0x03) << 4];
		memset(o, '=', 2); o += 2; break;
	}
	case 2: {
		*o++ = B64E[i[0] >> 2];
		*o++ = B64E[((i[0] & 0x03) << 4) | (i[1] >> 4)];
		*o++ = B64E[(i[1] & 0x0F) << 2];
		*o++ = '='; break;
	}
	}
	
	return o - dst;
}

/* Decode Base64 */
size_t b64decode(uint8_t *dst, uint8_t *src, size_t len) {
	register uint8_t *i = src, *o = dst;
	
	for (; src[len - 1] == '='; --len);
	
	for (; len >= 4; len -= 4) {
		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
		*o++ = (B64D[i[1]] << 4) | (B64D[i[2]] >> 2);
		*o++ = (B64D[i[2]] << 6) | (B64D[i[3]]); i += 4;
	}
	
	switch (len) {
	case 2: {
		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
		*o++ = (B64D[i[1]] << 4); break;
	}
	case 3: {
		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
		*o++ = (B64D[i[1]] << 4) | (B64D[i[2]] >> 2);
		*o++ = (B64D[i[2]] << 6); break;
	}
	}
	
	return o - dst;
}

static const uint8_t B64E[] = {
	'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
	'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
	'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

static const uint8_t B64D[] = {
	 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
	 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
	 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 62,  0,  0,  0, 63,
	52, 53, 54, 55, 56, 57, 58, 59, 60, 61,  0,  0,  0,  0,  0,  0,
	 0,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
	15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,  0,  0,  0,  0,  0,
	 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
	41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};