base64decode.cc (2259B)
1 2 #include "sys" 3 4 /* ========================================================================= 5 * The remainder of the code originates from http://base64.sourceforge.net/. 6 * The original version was written by Bob Trower. 7 * Adapted for C++ by me [kk] 8 * ========================================================================= 9 */ 10 11 /* 12 ** Translation Table as described in RFC1113 13 ** Not used during decode phase 14 static 15 const char *xx_cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 16 "abcdefghijklmnopqrstuvwxyz" 17 "0123456789+/"; 18 */ 19 20 /* 21 ** Translation Table to decode (created by author) 22 */ 23 static 24 const char *xx_cd64 = "|$$$}rstuvwxyz{$$$$$$$>?@" 25 "ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ" 26 "[\\]^_`abcdefghijklmnopq"; 27 28 /* 29 ** decodeblock 30 ** 31 ** decode 4 '6-bit' characters into 3 8-bit binary bytes 32 */ 33 static void decodeblock(char in[4], char out[4]) 34 { 35 out[0] = (unsigned char ) (in[0] << 2 | in[1] >> 4); 36 out[1] = (unsigned char ) (in[1] << 4 | in[2] >> 2); 37 out[2] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]); 38 } 39 40 /* 41 ** decode 42 ** 43 ** decode a base64 encoded stream discarding padding, line breaks and noise 44 */ 45 static 46 string base64_decode(char const *srcstr, int srclen) { 47 char in[4], out[4], v; 48 int i, j, len, morechars; 49 string decbuf; 50 int declen = 0; 51 52 /* Initialize. Only the first 3 chars of out will get overwritten. */ 53 out[3] = 0; 54 55 /* Examine all characters. */ 56 j = 0; 57 morechars = 1; 58 while (morechars) { 59 for (len = 0, i = 0; i < 4 && morechars; i++) { 60 v = 0; 61 62 while (morechars && !v) { 63 v = (unsigned char) srcstr[j++]; 64 if (j > srclen) 65 morechars = 0; 66 v = (unsigned char) ((v < 43 || v > 122) ? 67 0 : 68 xx_cd64[v - 43]); 69 if (v) 70 v = (unsigned char) ((v == '$') ? 0 : v - 61); 71 } 72 if (morechars) { 73 len++; 74 if (v) 75 in[i] = (unsigned char) (v - 1); 76 } 77 else 78 in[i] = 0; 79 } 80 if (len) { 81 decodeblock (in, out); 82 decbuf += string(out); 83 declen += len - 1; 84 } 85 } 86 87 /* All done. */ 88 return (decbuf); 89 } 90 91 string base64_decode(string const &s) { 92 return base64_decode(s.c_str(), s.length()); 93 }