Base64是MIME郵件中常用的編碼方式之一。它的主要思想是將輸入的字符串或數據編碼成只含有{'A'-'Z', 'a'-'z', '0'-'9', '+', '/'}這64個可打印字符的串,故稱爲“Base64”。
Base64編碼的方法是,將輸入數據流每次取6 bit,用此6 bit的值(0-63)作爲索引去查表,輸出相應字符。這樣,每3個字節將編碼爲4個字符(3×8 → 4×6);不滿4個字符的以'='填充。
const char EnBase64Tab[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int EncodeBase64(const unsigned char* pSrc, char* pDst, int nSrcLen, int nMaxLineLen)
{
unsigned char c1, c2, c3; // 輸入緩衝區讀出3個字節
int nDstLen = 0; // 輸出的字符計數
int nLineLen = 0; // 輸出的行長度計數
int nDiv = nSrcLen / 3; // 輸入數據長度除以3得到的倍數
int nMod = nSrcLen % 3; // 輸入數據長度除以3得到的餘數
// 每次取3個字節,編碼成4個字符
for (int i = 0; i < nDiv; i ++)
{
// 取3個字節
c1 = *pSrc++;
c2 = *pSrc++;
c3 = *pSrc++;
// 編碼成4個字符
*pDst++ = EnBase64Tab[c1 >> 2];
*pDst++ = EnBase64Tab[((c1 << 4) | (c2 >> 4)) & 0x3f];
*pDst++ = EnBase64Tab[((c2 << 2) | (c3 >> 6)) & 0x3f];
*pDst++ = EnBase64Tab[c3 & 0x3f];
nLineLen += 4;
nDstLen += 4;
// 輸出換行?
if (nLineLen > nMaxLineLen - 4)
{
*pDst++ = '/r';
*pDst++ = '/n';
nLineLen = 0;
nDstLen += 2;
}
}
// 編碼餘下的字節
if (nMod == 1)
{
c1 = *pSrc++;
*pDst++ = EnBase64Tab[(c1 & 0xfc) >> 2];
*pDst++ = EnBase64Tab[((c1 & 0x03) << 4)];
*pDst++ = '=';
*pDst++ = '=';
nLineLen += 4;
nDstLen += 4;
}
else if (nMod == 2)
{
c1 = *pSrc++;
c2 = *pSrc++;
*pDst++ = EnBase64Tab[(c1 & 0xfc) >> 2];
*pDst++ = EnBase64Tab[((c1 & 0x03) << 4) | ((c2 & 0xf0) >> 4)];
*pDst++ = EnBase64Tab[((c2 & 0x0f) << 2)];
*pDst++ = '=';
nDstLen += 4;
}
// 輸出加個結束符
*pDst = '/0';
return nDstLen;
}
Base64解碼方法中,最簡單的也是查表法:將64個可打印字符的值作爲索引,查表得到的值(範圍爲0-63)依次連起來,拼湊成字節形式輸出,就得到解碼結果。
const char DeBase64Tab[] =
{
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'-'9'
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, // 'A'-'Z'
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, // 'a'-'z'
};
int DecodeBase64(const char* pSrc, unsigned char* pDst, int nSrcLen)
{
int nDstLen; // 輸出的字符計數
int nValue; // 解碼用到的長整數
int i;
i = 0;
nDstLen = 0;
// 取4個字符,解碼到一個長整數,再經過移位得到3個字節
while (i < nSrcLen)
{
if (*pSrc != '/r' && *pSrc!='/n')
{
nValue = DeBase64Tab[*pSrc++] << 18;
nValue += DeBase64Tab[*pSrc++] << 12;
*pDst++ = (nValue & 0x00ff0000) >> 16;
nDstLen++;
if (*pSrc != '=')
{
nValue += DeBase64Tab[*pSrc++] << 6;
*pDst++ = (nValue & 0x0000ff00) >> 8;
nDstLen++;
if (*pSrc != '=')
{
nValue += DeBase64Tab[*pSrc++];
*pDst++ =nValue & 0x000000ff;
nDstLen++;
}
}
i += 4;
}
else // 回車換行,跳過
{
pSrc++;
i++;
}
}
// 輸出加個結束符
*pDst = '/0';
return nDstLen;
}