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 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
/*
* Written by Poul-Henning Kamp <phk@phk.freebsd.dk>
*
* This file is in the public domain.
*
* $Id: base64.c 1092 2006-09-18 22:03:54Z phk $
*/
#include <sys/types.h>
#include <stdint.h>
#include "varnishapi.h"
static const char *b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static char i64[256];
void
base64_init(void)
{
int i;
const char *p;
for (i = 0; i < 256; i++)
i64[i] = -1;
for (p = b64, i = 0; *p; p++, i++)
i64[(int)*p] = i;
i64['='] = 0;
}
int
base64_decode(char *d, unsigned dlen, const char *s)
{
unsigned u, v, l;
int i;
u = 0;
l = 0;
while (*s) {
for (v = 0; v < 4; v++) {
if (!*s)
break;
i = i64[(int)*s++];
if (i < 0)
return (-1);
u <<= 6;
u |= i;
}
for (v = 0; v < 3; v++) {
if (l >= dlen - 1)
return (-1);
*d = (u >> 16) & 0xff;
u <<= 8;
l++;
d++;
}
}
*d = '\0';
return (0);
}
#ifdef TEST_DRIVER
#include <stdio.h>
const char *test1 =
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
int
main(int argc, char **argv)
{
int i;
char buf[BUFSIZ];
unsigned l;
(void)argc;
(void)argv;
base64_init();
l = sizeof buf;
base64_decode(buf, &l, test1);
printf("%s\n", buf);
return (0);
}
#endif
|