1 #include "base32decode.h"
2 
3 static const unsigned char base32values[128] = {
4     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
5     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
6     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
7     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
8     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
9     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
10     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
11     0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
12     0xff, 0xff, 0x0a, 0x0b, 0x0c, 0xff, 0x0d, 0x0e,
13     0x0f, 0xff, 0x10, 0x11, 0x12, 0x13, 0x14, 0xff,
14     0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
15     0x1d, 0x1e, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
16     0xff, 0xff, 0x0a, 0x0b, 0x0c, 0xff, 0x0d, 0x0e,
17     0x0f, 0xff, 0x10, 0x11, 0x12, 0x13, 0x14, 0xff,
18     0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
19     0x1d, 0x1e, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff
20 };
21 
base32decode(unsigned char * out,long long outlen,const unsigned char * in,long long inlen)22 int base32decode(unsigned char *out, long long outlen, const unsigned char *in, long long inlen) {
23 
24     long long i, j = 0;
25     unsigned char u;
26     unsigned long long v = 0, vbits = 0;
27 
28     for (i = 0; i < inlen; ++i) {
29 
30         if (in[j] & 0x80) return 0;
31         u = base32values[in[i]];
32         if (u > 0x1f) return 0;
33         v |= u << vbits;
34         vbits += 5;
35 
36         if (vbits >= 8) {
37             if (j >= outlen) return 0;
38             out[j++] = v;
39             vbits -= 8;
40             v >>= 8;
41         }
42     }
43     if (vbits) {
44         if (j >= outlen) return 0;
45         out[j++] = v;
46     }
47     return 1;
48 }
49