00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <string.h>
00023
00024 char my_base64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
00025
00026
00027
00028 int base64_to_raw(char * in, int len_in, char * out, int len_out)
00029 {
00030 int n_in;
00031 int counter=0;
00032 int n_out=0;
00033 char* c;
00034 unsigned int buf=0;
00035 for (n_in=0 ; n_in<len_in && n_out<len_out ; n_in++) {
00036
00037 if (in[n_in] == '=')
00038 break;
00039
00040 c = strchr(my_base64, in[n_in]);
00041
00042
00043 if (c == NULL)
00044 continue;
00045
00046 buf <<= 6;
00047 buf += (int)(c-my_base64);
00048 counter+=6;
00049
00050 if (counter < 8)
00051 continue;
00052
00053 if (n_out >= len_out)
00054 return -1;
00055
00056 out[n_out++] = (buf>>(counter-8)) & 0xFF;
00057 counter -= 8;
00058 }
00059
00060
00061 if (counter == 0 && (n_in+1 >= len_in || in[n_in] != '=')) {
00062 return n_out;
00063 }
00064
00065
00066 if (counter == 2 && (in[n_in] == '=') &&
00067 (n_in+1 >= len_in || in[n_in] != '=')) {
00068 return n_out;
00069 }
00070
00071
00072 if (counter == 4 && (in[n_in] == '=') &&
00073 n_in+1 < len_in && in[n_in+1] == '=') {
00074 return n_out;
00075 }
00076
00077
00078 return -1;
00079 }
00080
00081
00082
00083
00084 int raw_to_base64(char *in, int len_in, char * out, int len_out)
00085 {
00086 int n_in;
00087 int counter=0;
00088 int n_out=0;
00089 unsigned int buf=0;
00090
00091 for (n_in=0 ; n_in<len_in && n_out<len_out ; n_in++) {
00092 buf <<= 8;
00093 buf += (unsigned char)(in[n_in]);
00094 counter+=8;
00095
00096 while(counter>=6) {
00097 if (n_out>=len_out)
00098 return -1;
00099 out[n_out++] = my_base64[(buf>>(counter-6)) & 0x3F];
00100 counter-=6;
00101 }
00102 }
00103
00104
00105 if (counter) {
00106 if (n_out >= len_out)
00107 return -1;
00108
00109 out[n_out++] = my_base64[(buf<<(6-counter)) & 0x3F];
00110
00111 if (n_out >= len_out)
00112 return -1;
00113
00114
00115 out[n_out++] = '=';
00116
00117 if (n_out >= len_out)
00118 return -1;
00119
00120
00121 if (counter==2) {
00122 out[n_out++] = '=';
00123 }
00124 }
00125
00126 return n_out;
00127 }