Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节。
Code:
#define UNDEFINE_BASE64_DECODECHAR (0xFF)
#define _BAD UNDEFINE_BASE64_DECODECHAR
const unsigned char Base64_EncodeTable[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const unsigned char Base64_DecodeTable[128] = {
_BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, _BAD, _BAD, 0x3E, _BAD, _BAD, _BAD, 0x3F,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
0x3C, 0x3D, _BAD, _BAD, _BAD, 0x00, _BAD, _BAD,
_BAD, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, _BAD, _BAD, _BAD, _BAD, _BAD,
_BAD, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
0x31, 0x32, 0x33, _BAD, _BAD, _BAD, _BAD, _BAD
};
int Base64_Encode(unsigned char* pSStr, unsigned char* pDStr)
{
int len = (int)strlen(reinterpret_cast<const char*>(pSStr));
int equ_num = len%3;
int i = 0;
int dStrLen = 0;
for(i = 0, dStrLen = 0; i <= len - 3; i += 3, dStrLen += 4){
pDStr[dStrLen] = (pSStr[i]>>2)&0x3F;
pDStr[dStrLen + 1] = (((pSStr[i]<<6)>>2)&0x30)|((pSStr[i + 1]>>4)&0x0F);
pDStr[dStrLen + 2] = (((pSStr[i + 1]<<4)>>2)&0x3C)|((pSStr[i + 2]>>6)&0x03);
pDStr[dStrLen + 3] = pSStr[i + 2]&0x3F;
}
if(0 != equ_num){
unsigned char ch1 = ((2 == equ_num) ? pSStr[len - 2] : pSStr[len - 1]);
unsigned char ch2 = ((2 == equ_num) ? pSStr[len - 1] : 0);
pDStr[dStrLen++] = (ch1>>2)&0x3F;
pDStr[dStrLen++] = (((ch1<<6)>>2)&0x30)|((ch2>>4)&0x0F);
if(0 != ch2){
pDStr[dStrLen++] = ((ch2<<4)>>2)&0x3C;
}
}
for(i = 0; i < dStrLen; i++){
pDStr[i] = Base64_EncodeTable[pDStr[i]];
}
if(0 != equ_num){
if(1 == equ_num){
pDStr[dStrLen++] = '=';
}
pDStr[dStrLen++] = '=';
}
pDStr[dStrLen] = 0;
return dStrLen;
}
int Base64_Decode(unsigned char* pSStr, unsigned char* pDStr)
{
int len = (int)strlen(reinterpret_cast<const char*>(pSStr));
int dStrLen = 0;
int i = 0;
unsigned char ch1 = 0;
unsigned char ch2 = 0;
unsigned char ch3 = 0;
unsigned char ch4 = 0;
for(i = 0, dStrLen = 0; i < len; i += 4, dStrLen += 3){
ch1 = Base64_DecodeTable[pSStr[i]];
ch2 = Base64_DecodeTable[pSStr[i + 1]];
ch3 = Base64_DecodeTable[pSStr[i + 2]];
ch4 = Base64_DecodeTable[pSStr[i + 3]];
pDStr[dStrLen] = ((ch1<<2)&0xFC)|((ch2>>4)&0x03);
pDStr[dStrLen + 1] = ((ch2<<4)&0xF0)|((ch3>>2)&0x0F);
pDStr[dStrLen + 2] = ((ch3<<6)&0xC0)|(ch4&0x3F);
}
pDStr[dStrLen] = 0;
return dStrLen;
}
posted on 2011-08-01 23:31
Lshain 阅读(276)
评论(0) 编辑 收藏 引用 所属分类:
协议分析