29 static const char lookup_table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30 static const char pad =
'=';
33 static char *b64_encode (
const uint8_t * buffer,
size_t len )
41 size_t buf_len = 4*(len/3) + 4 + 1;
43 p = out =
alloc(buf_len);
45 const uint8_t * cur = buffer;
46 for(
size_t i = 0; i < len/3; i++) {
47 temp = ( *cur++ ) << 16;
48 temp += ( *cur++ ) << 8;
51 *p++ = lookup_table[( temp & 0x00FC0000 ) >> 18];
52 *p++ = lookup_table[( temp & 0x0003F000 ) >> 12];
53 *p++ = lookup_table[( temp & 0x00000FC0 ) >> 6 ];
54 *p++ = lookup_table[( temp & 0x0000003F ) ];
58 temp = ( *cur++ ) << 16;
59 *p++ = lookup_table[( temp & 0x00FC0000 ) >> 18];
60 *p++ = lookup_table[( temp & 0x0003F000 ) >> 12];
65 temp = ( *cur++ ) << 16;
66 temp += ( *cur++ ) << 8;
67 *p++ = lookup_table[( temp & 0x00FC0000 ) >> 18];
68 *p++ = lookup_table[( temp & 0x0003F000 ) >> 12];
69 *p++ = lookup_table[( temp & 0x00000FC0 ) >> 6 ];
78 static size_t b64_length(
const char *input,
size_t len) {
80 input[len-2] == pad? 2 :
81 input[len-1] == pad? 1 : 0;
83 return 3*len/4 - padding;
86 static uint8_t *b64_decode (
const char *input,
size_t len ,
size_t *out_size)
92 *out_size = b64_length(input, len);
95 uint8_t *p = out =
alloc(*out_size);
98 const char * cur = input;
99 while ( cur < input + len ) {
100 for (
size_t i = 0; i < 4; i++ ) {
102 if ( *cur >= 0x41 && *cur <= 0x5A ) {
104 }
else if ( *cur >= 0x61 && *cur <= 0x7A ) {
106 }
else if ( *cur >= 0x30 && *cur <= 0x39 ) {
108 }
else if ( *cur == 0x2B ) {
110 }
else if ( *cur == 0x2F ) {
112 }
else if ( *cur == pad ) {
113 switch ( input + len - cur ) {
115 *p++ = ( ( temp >> 16 ) & 0x000000FF );
116 *p++ = ( ( temp >> 8 ) & 0x000000FF );
119 *p++ = ( ( temp >> 10 ) & 0x000000FF );
129 *p++ = ( ( temp >> 16 ) & 0x000000FF );
130 *p++ = ( ( temp >> 8 ) & 0x000000FF );
131 *p++ = ( ( temp ) & 0x000000FF );
145 size_t b64_len = strlen(b64);
148 uint8_t * b = b64_decode(b64, b64_len, &b_len);
char * tc_bytes_b64(const bytes_t *b)
Structure that's stores a pointer that points to data_len bytes.
void * alloc(size_t size)
bytes_t * tc_init_bytes(void *bs, size_t len)
bytes_t * tc_b64_bytes(const char *b64)