ITPub博客

首页 > Linux操作系统 > Linux操作系统 > base64 加密解密函数

base64 加密解密函数

原创 Linux操作系统 作者:李飞java 时间:2009-09-16 11:07:54 0 删除 编辑

CString Base64Encode(LPCTSTR lpszSrc)
{
ASSERT(lpszSrc != NULL && AfxIsValidString(lpszSrc));
const char BASE64_ENCODE_TABLE[64] = {
65, 66, 67, 68, 69, 70, 71, 72, // 00 - 07
73, 74, 75, 76, 77, 78, 79, 80, // 08 - 15
81, 82, 83, 84, 85, 86, 87, 88, // 16 - 23
89, 90, 97, 98, 99, 100, 101, 102, // 24 - 31
103, 104, 105, 106, 107, 108, 109, 110, // 32 - 39
111, 112, 113, 114, 115, 116, 117, 118, // 40 - 47
119, 120, 121, 122, 48, 49, 50, 51, // 48 - 55
52, 53, 54, 55, 56, 57, 43, 47 };// 56 - 63

unsigned int iTest;

LPCTSTR pInBuffer=lpszSrc;

int nSize = (int)_tcslen(lpszSrc);
char* pOutBuffer=new char[nSize/3*4 5];
ZeroMemory(pOutBuffer,nSize/3*4 5);

for(UINT i=0;i<_tcslen(lpszSrc) / 3;i )
{
iTest = (unsigned char) *pInBuffer ;
iTest = iTest << 8;

iTest = iTest | (unsigned char) *pInBuffer ;
iTest = iTest << 8;

iTest = iTest | (unsigned char) *pInBuffer ;

http://www.mscto.com

//以4 byte倒序写入输出缓冲
pOutBuffer[3] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[2] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[1] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[0] = BASE64_ENCODE_TABLE[iTest];
pOutBuffer =4;
}

//设置尾部
switch (_tcslen(lpszSrc) % 3)
{
case 0:
break;
case 1:
iTest = (unsigned char) *pInBuffer;
iTest = iTest << 4;
pOutBuffer[1] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[0] = BASE64_ENCODE_TABLE[iTest];
pOutBuffer[2] = '='; //用'='也就是64码填充剩余部分
pOutBuffer[3] = '=';
break;
case 2:
iTest = (unsigned char) *pInBuffer ;
iTest = iTest << 8;
iTest = iTest | (unsigned char) *pInBuffer;
iTest = iTest << 2;
pOutBuffer[2] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[1] = BASE64_ENCODE_TABLE[iTest & 0x3F];
iTest = iTest >> 6;
pOutBuffer[0] = BASE64_ENCODE_TABLE[iTest];
pOutBuffer[3] = '='; // Fill remaining byte.
break;
}
pOutBuffer-=nSize/3*4;
CString strEncode=pOutBuffer;
delete [] pOutBuffer;


pOutBuffer=NULL;
return strEncode;
}

CString Base64Decode(LPCTSTR lpszSrc)
{
ASSERT(lpszSrc != NULL && AfxIsValidString(lpszSrc));
const unsigned int BASE64_DECODE_TABLE[256] = {
255, 255, 255, 255, 255, 255, 255, 255, // 00 - 07
255, 255, 255, 255, 255, 255, 255, 255, // 08 - 15
255, 255, 255, 255, 255, 255, 255, 255, // 16 - 23

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22434610/viewspace-614772/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-09-02

  • 博文量
    42
  • 访问量
    56886