atob() has been replaced with a lookup table, removing previous conditionals and function calls necessary to decode.
107 lines
2.9 KiB
C
107 lines
2.9 KiB
C
#include "encode.h"
|
|
|
|
#define PADDING '='
|
|
|
|
static
|
|
unsigned char b64toascii[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
|
|
"abcdefghijklmnopqrstuvwxyz" \
|
|
"0123456789" \
|
|
"+/";
|
|
|
|
static
|
|
unsigned char b64urltoascii[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
|
|
"abcdefghijklmnopqrstuvwxyz" \
|
|
"0123456789" \
|
|
"-_";
|
|
|
|
static
|
|
unsigned char asciitob64[] = {
|
|
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, 62, 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, 63, 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
|
|
};
|
|
|
|
|
|
int
|
|
encode(unsigned char *op, int olen, unsigned char *sp, int url)
|
|
{
|
|
int tmp;
|
|
unsigned char *table;
|
|
unsigned char *sbeg;
|
|
unsigned char *tend;
|
|
|
|
table = (!url) ? b64toascii : b64urltoascii;
|
|
|
|
sbeg = sp;
|
|
tend = op + olen - (olen % 3);
|
|
while (op < tend) {
|
|
*sp++ = table[(*op & ~3) >> 2];
|
|
tmp = (*op++ & 3) << 4;
|
|
*sp++ = table[tmp + ((*op & ~15) >> 4)];
|
|
tmp = (*op++ & 15) << 2;
|
|
*sp++ = table[tmp + ((*op & 192) >> 6)];
|
|
*sp++ = table[*op++ & ~192];
|
|
}
|
|
switch (olen % 3) {
|
|
case 2:
|
|
*sp++ = table[(*op & ~3) >> 2];
|
|
tmp = (*op++ & 3) << 4;
|
|
*sp++ = table[tmp + ((*op & ~15) >> 4)];
|
|
*sp++ = table[(*op & 15) << 2];
|
|
*sp++ = PADDING;
|
|
break;
|
|
case 1:
|
|
*sp++ = table[(*op & ~3) >> 2];
|
|
*sp++ = table[(*op & 3) << 4];
|
|
*sp++ = PADDING;
|
|
*sp++ = PADDING;
|
|
break;
|
|
}
|
|
|
|
return sp-sbeg;
|
|
}
|
|
|
|
int
|
|
decode(unsigned char *sp, int slen, unsigned char *op)
|
|
{
|
|
int tmp, b;
|
|
unsigned char *obeg;
|
|
unsigned char *qend;
|
|
|
|
obeg = op;
|
|
qend = sp + slen - (slen % 4);
|
|
while (sp < qend) {
|
|
tmp = asciitob64[*sp++] << 2;
|
|
b = asciitob64[*sp++];
|
|
*op++ = tmp + ((b & ~15) >> 4);
|
|
tmp = (b & 15) << 4;
|
|
b = asciitob64[*sp++];
|
|
*op++ = tmp + ((b & ~3) >> 2);
|
|
*op++ = ((b & 3) << 6) + asciitob64[*sp++];
|
|
}
|
|
switch (slen % 4) {
|
|
case 3:
|
|
tmp = asciitob64[*sp++] << 2;
|
|
b = asciitob64[*sp++];
|
|
*op++ = tmp + ((b & ~15) >> 4);
|
|
tmp = (b & 15) << 4;
|
|
*op++ = tmp + ((asciitob64[*sp++] & ~3) >> 2);
|
|
break;
|
|
case 2:
|
|
tmp = asciitob64[*sp++] << 2;
|
|
*op++ = tmp + ((asciitob64[*sp++] & ~15) >> 4);
|
|
break;
|
|
}
|
|
|
|
return op-obeg;
|
|
}
|