#include <stdio.h>
#include <memory.h>
/* ascii --> index */
unsigned char base64_table[] = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/"
};
/* index --> ascii */
unsigned char base64_index[] = {
62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,
255,255,255,255,255,255,255,
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,
255,255,255,255,255,255,
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 base64_encode(const unsigned char* input, unsigned char* output)
{
if (NULL == input || NULL == output)
return -1;
unsigned int in_len = strlen(input);
if (0 == in_len)
return -1;
unsigned int i = 0;
int j = 0;
for (i=0; i<in_len; )
{
unsigned char index = input[i] >> 2;
output[j++] = base64_table[index];
if (i+1 == in_len)
{
index = (unsigned char)(input[i] << 6) >> 2;
output[j++] = base64_table[index];
output[j++] = '=';
output[j++] = '=';
break;
}
index = (unsigned char)(input[i] << 6) >> 2 | input[i+1] >> 4;
output[j++] = base64_table[index];
if (i+2 == in_len)
{
index = (unsigned char)(input[i+1] << 4) >> 2;
output[j++] = base64_table[index];
output[j++] = '=';
break;
}
index = (unsigned char)(input[i+1] << 4) >> 2 | input[i+2] >> 6;
output[j++] = base64_table[index];
index = (unsigned char)(input[i+2] << 2) >> 2;
output[j++] = base64_table[index];
i += 3;
}
return j;
}
int base64_decode(const unsigned char* input, unsigned char* output)
{
if (NULL == input || NULL == output)
return -1;
unsigned int in_len = strlen(input);
if (0 == in_len)
return -1;
unsigned int i = 0;
int j = 0;
for (i=0; i<in_len; i+=4)
{
unsigned char buf[4] = {0};
buf[0] = base64_index[input[i]-'+'];
buf[1] = base64_index[input[i+1]-'+'];
unsigned char c = buf[0] << 2 | buf[1] >> 4;
output[j++] = c;
if ('=' == input[i+2])
break;
buf[2] = base64_index[input[i+2]-'+'];
c = buf[1] << 4 | buf[2] >> 2;
output[j++] = c;
if ('=' == input[i+3])
break;
buf[3] = base64_index[input[i+3]-'+'];
c = buf[2] << 6 | buf[3];
output[j++] = c;
}
return j;
}
转载于:https://my.oschina.net/jiuyueshouyi/blog/486430