base64編解碼的兩個函數,聲明,參考網絡上的代碼實現。
unsigned char *base64_encode(unsigned char *str, long* lpBufLen)
{
long len;
long str_len;
unsigned char *res;
int i,j;
//定義base64編碼表
const unsigned char *base64_table = (const unsigned char *)("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
//計算經過base64編碼后的字符串長度
str_len=strlen((char*)str);
if(str_len % 3 == 0)
len=str_len/3*4;
else
len=(str_len/3+1)*4;
if (NULL != lpBufLen) {
*lpBufLen = len;
}
res = (unsigned char *)malloc(sizeof(unsigned char)*len+1);
res[len]='\0';
//以3個8位字符為一組進行編碼
for(i=0,j=0;i<len-2;j+=3,i+=4)
{
res[i]=base64_table[str[j]>>2]; //取出第一個字符的前6位並找出對應的結果字符
res[i+1]=base64_table[(str[j]&0x3)<<4 | (str[j+1]>>4)]; //將第一個字符的后位與第二個字符的前4位進行組合並找到對應的結果字符
res[i+2]=base64_table[(str[j+1]&0xf)<<2 | (str[j+2]>>6)]; //將第二個字符的后4位與第三個字符的前2位組合並找出對應的結果字符
res[i+3]=base64_table[str[j+2]&0x3f]; //取出第三個字符的后6位並找出結果字符
}
switch(str_len % 3)
{
case 1:
res[i-2]='=';
res[i-1]='=';
break;
case 2:
res[i-1]='=';
break;
}
return res;
}
unsigned char *base64_decode(unsigned char *code, long* lpBufLen)
{
//根據base64表,以字符找到對應的十進制數據
int table[]={0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,62,0,0,0,
63,52,53,54,55,56,57,58,
59,60,61,0,0,0,0,0,0,0,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,0,0,0,0,0,0,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
};
long len;
long str_len;
unsigned char *res;
int i,j;
//計算解碼后的字符串長度
len=strlen((char*)code);
//判斷編碼后的字符串后是否有=
if(strstr((char*)code,"=="))
str_len=len/4*3-2;
else if(strstr((char*)code,"="))
str_len=len/4*3-1;
else
str_len=len/4*3;
if (NULL != lpBufLen) {
*lpBufLen = str_len;
}
res=(unsigned char*)malloc(sizeof(unsigned char)*str_len+1);
res[str_len]='\0';
//以4個字符為一位進行解碼
for(i=0,j=0;i < len-2;j+=3,i+=4)
{
res[j]=((unsigned char)table[code[i]])<<2 | (((unsigned char)table[code[i+1]])>>4); //取出第一個字符對應base64表的十進制數的前6位與第二個字符對應base64表的十進制數的后2位進行組合
res[j+1]=(((unsigned char)table[code[i+1]])<<4) | (((unsigned char)table[code[i+2]])>>2); //取出第二個字符對應base64表的十進制數的后4位與第三個字符對應bas464表的十進制數的后4位進行組合
res[j+2]=(((unsigned char)table[code[i+2]])<<6) | ((unsigned char)table[code[i+3]]); //取出第三個字符對應base64表的十進制數的后2位與第4個字符進行組合
}
return res;
}
