const unsigned char TAB[] = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklnmopqrstuvwxyz123456789+/";
/*
函数功能:base64编码
形参:
input输入的数据流
inlen输入的数据流长度
output输出的字符串
返回值:编码以后的有效字符串长度
*/
int base64_encode( unsigned char *input, int inlen,unsigned char *output)
{
int i = 0, j = 0;
unsigned char com_byte = inlen % 3;
switch(com_byte)
{
case 0:com_byte = 0;
break;
case 1:com_byte = 2;
break;
case 2:com_byte = 1;
break;
default:break;
}
inlen += com_byte;
for(i = 0,j = 0;i < inlen;i+=3,j+=4)
{
output[j] = TAB[input[i] >> 2];
output[j+1] = TAB[(input[i]&0x3)<<4 | (input[i+1] >> 4)];
output[j+2] = TAB[(input[i+1]&0xf) << 2 | (input[i+2] >> 6)];
output[j+3] = TAB[input[i+2]&0x3f];
}
if(com_byte == 1)
output[j - 1] = '=';
else if(com_byte == 2)
{
output[j - 1] = '=';
output[j - 2] = '=';
}
output[j] = 0;
return j;
}
/*
函数功能:base64解码
形参:
input输入的字符串
inlen输入的字符串长度
output输出的数据流
返回值:解码以后的有效数据流长度
*/
int base64_decode( unsigned char *input, int inlen,unsigned char *output)
{
int i = 0, j = 0;
unsigned char temp[100];
for(i = 0;i < inlen;i++)
{
for(j = 0;j < strlen(TAB);j++)
{
if(TAB[j] == input[i])
{
temp[i] = j;
break;
}
}
}
for(i = 0,j = 0;i < inlen;i+=4,j+=3)
{
output[j] = temp[i] << 2 | ((temp[i+1] >> 4) & 0x3);
output[j+1] = ((temp[i+1]&0xf) << 4) | ((temp[i+2] >> 2) & 0xf);
output[j+2] = ((temp[i+2]&0x3) << 6) | (temp[i+3]& 0x3f);
}
if(input[inlen - 1] == '=')
{
if(input[inlen - 2] != '=')
{
output[j - 1] = 0;
j -= 1;
}
else
{
output[j - 1] = 0;
output[j - 2] = 0;
j -= 2;
}
}
else
output[j] = 0;
return j;
}
int main(void)
{
unsigned char a[] = {1,2,3,4,5,6,7};
unsigned char b[] = "AQIDBAUGBw==";
int i = 0;
int outlen = 0;
unsigned char encodebuf[100];
unsigned char decodebuf[100];
outlen = base64_encode(a, sizeof(a), encodebuf);
printf("编码后字符串为 = %s\n", encodebuf);
printf("编码后的字符串长度为 = %d\n", outlen);
outlen = base64_decode(b, sizeof(b) - 1, decodebuf);//-1是因为sizeof还包含了结束符,实际结束符是不参与运算的
printf("解码后的buf数据长度为 = %d\n", outlen);
printf("解码后的buf数据为 = \n");
for(i = 0; i < outlen; i++)
printf("%d ", decodebuf[i]);
}