///
// DWORD DecodeBase64(LPBYTE lpDes, DWORD dwDesLen, LPCTSTR lpSrc)
// 参数:
// LPBYTE lpDes 数组地址
// DWORD dwDesLen 数组大小
// LPCTSTR lpSrc 要解码的字符串地址
//
// 返回值为数据的真实长度;
///
DWORD DecodeBase64(LPBYTE lpDes, DWORD dwDesLen, LPCTSTR lpSrc)
{
DWORD dwLength = lstrlen(lpSrc);
if( 0!=dwLength%4 ) //不是 4 的倍数,认为是损坏的数据
return 0;
if( (dwDesLen/3) < (dwLength/4) ) //缓冲区不够大
return 0;
DWORD len = dwLength/4; //循环次数
LPBYTE lpBufDes = NULL;
LPBYTE lpBufSrc = NULL;
lpBufDes = new BYTE [ 3*len +1 ];
lpBufSrc = new BYTE [ 4*len +1 ];
memset( lpBufDes, 0, 3*len+1 );
memset( lpBufSrc, 0, 4*len+1 );
LPBYTE lpTmpDes = lpBufSrc;
LPBYTE lpTmpSrc = (LPBYTE)lpSrc;
//转换字符
TCHAR* pszAddress=NULL;
for(DWORD i=0; i<dwLength; i++)
{
pszAddress = strchr( base64_alphabet, *lpTmpSrc );
if( pszAddress==NULL ) return FALSE;
*lpTmpDes = pszAddress - base64_alphabet;
//注:这里已经考虑字符'='了, 字符'='的下标是64,二进制是 01000000 ,在下面的转换中,前两位无效,仍然为0
lpTmpSrc++;
lpTmpDes++;
}
//开始解码
lpTmpDes = lpBufDes;
lpTmpSrc = lpBufSrc;
for(i=0; i<len; i++)
{
*lpTmpDes = ( (*lpTmpSrc&0x3f)<<2 ) + ( (*(lpTmpSrc+1)&0x30)>>4 );
*(lpTmpDes+1) = ( (*(lpTmpSrc+1)&0xf)<<4 ) + ( (*(lpTmpSrc+2)&0x3c)>>2 );
*(lpTmpDes+2) = ( (*(lpTmpSrc+2)&0x3)<<6 ) + ( *(lpTmpSrc+3)&0x3f );
lpTmpSrc += 4;
lpTmpDes += 3;
}
//计算原字符串尾部有一个还是二个 '='
DWORD count = 0;
if( *(lpSrc+dwLength-1) == '=')
{
count += 1;
if( *(lpSrc+dwLength-2) == '=')
{
count += 1;
}
}
memcpy(lpDes, lpBufDes, 3*len - count);
delete [] lpBufDes;
delete [] lpBufSrc;
return 3*len-count;
}