base64编解码
#define _BASE64_INCLUDE__H__ #include //************************************************************************************* // 定义Base64编码命名空间: //************************************************************************************* namespace stringcoding { static const char _B64_[64]={ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; //-------------------------------------------------- //Encodeing: //-------------------------------------------------- inline void encodetribyte(unsigned char * in,unsigned char * out,intlen) { if(len==0) return; inti; unsigned char inbuf[3]; memset(inbuf,0,sizeof(unsigned char)*3); for(i=0;i out[0]=_B64_[ inbuf[0]>>2 ]; out[1]=_B64_[ ((inbuf[0]&0x03)<<4)|((inbuf[1]&0xf0)>>4) ]; //if(len>1) means len=={2,3} //else means len==1, out[2]='='; out[2]=(len>1?_B64_[ ((inbuf[1]&0x0f)<<2)|((inbuf[2]&0xc0)>>6) ]:'='); //if(len>2) menaslen==3 //else means len=={1,2} out[3]='='; out[3]=(len>2?_B64_[ inbuf[2]&0x3f ]:'='); } //-------------------------------------------------- //Decoding: //-------------------------------------------------- inline intdecodetribyte(unsigned char * in, unsigned char * out) { inti,j,len; char dec[4]; memset(dec,0,sizeof(char)*4); len=3; //Get effective original text char count: if(in[3]=='=') len--; if(in[2]=='=') len--; //Find code according to input charactors: for(i=0;i<64;i++) { for(j=0;j<4;j++) { if(in[j]==_B64_[i]) dec[j]=i; } } //Re-compose original text code: out[0]=(dec[0]<<2|dec[1]>>4); if(len==1) return 1; out[1]=(dec[1]<<4|dec[2]>>2); if(len==2) return 2; out[2]=(((dec[2]<<6)&0xc0)|dec[3]); return 3; } //Encode input byte stream, please ensure lenghth of out //buffer big enough to hold all codes. //The b64 code array size is 4*(tri-byte blocks in original text). inline int Base64Encode(unsigned char * b64,const unsigned char * input,ULONGstringlen=0) { if(!b64||!input||stringlen<0) return 0; ULONG slen,imax; register unsigned inti,idin,idout; intrd,re,len; slen=(stringlen)?stringlen:strlen((char *)input); if(slen==0) return 0; rd=slen%3; rd=(rd==0)?3:rd; //Maximun tri-byte blocks: imax=(slen+(3-rd))/3-1; for(i=0;i<=imax;i++) { idin =i*3; idout=i*4; len=(i==imax)?rd:3; encodetribyte((unsigned char *)&input[idin],&b64[idout],len); } re=(imax+1)*4; b64[re]='\\0'; return re; } //Decode input byte stream, please ensure lenghth of out //buffer big enough to hold all codes. //The b64 code array size is about 3*(quad-byte blocks in b64 code). inline int Base64Decode(unsigned char * output,const unsigned char * b64,ULONG codelen=0) { if(!output||!b64||codelen<0) return 0; ULONG slen,imax; register unsigned inti,idin,idout; intrd,re,len; slen=(codelen)?codelen:strlen((char *)b64); if(slen<4) return 0; rd=slen%4; if(rd!=0) return 0; //Code error!. imax=slen/4-1; for(i=0;i<=imax;i++) { idin =i*4; idout=i*3; len=decodetribyte((unsigned char *)&b64[idin],&output[idout]); } re=(imax*3)+len; output[re]='\\0'; return re; } //----------------------------------------------------------------------------------------- //-------------------------------------------------- // Convert CString to char * string // Return string length: //-------------------------------------------------- inline unsigned char * CString2Char(constCString&str,int& converted) { UINT len; DWORD error; unsigned char * buf=0; if(str==L\"\") return 0; len=str.GetLength()*sizeof(TCHAR)/sizeof(unsigned char)+1; buf=new unsigned char[len]; memset(buf,0,sizeof(unsigned char)*len); converted=WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),(char *)buf,len,0,0); if(converted==0) { error=GetLastError(); } return buf; } //---------------------------------------- // 对CString字符串进行base64编码, // 编码后字符串变长大约1/3: //---------------------------------------- inline CStringStringBase64Encode(CString& text) { CStringdest; unsigned char * bufchar=0,* buf64=0; UINT sz,bytes; //............................................ // Convert text (Unicode) to UTF-8: //............................................ //A. Get buffer size when converted to UTF-8. // Remember to add one byte to hold '\\0': bytes=WideCharToMultiByte(CP_UTF8,0,text.GetBuffer(),text.GetLength(),NULL,0,0,0); //B. Convert string to UTF-8 format: sz=bytes+1; bufchar=new unsigned char[sz]; memset(bufchar,0,sizeof(unsigned char)*sz); WideCharToMultiByte(CP_UTF8,0,text.GetBuffer(),text.GetLength(),(char *)bufchar,bytes,0,0); //............................................ // Convert UTF-8 to base64 code: //............................................ sz=(bytes+(3-bytes%3))/3*4+1; buf64=new unsigned char[sz]; //Multiply 2 to avoid memory overflow. memset(buf64,0,sizeof(unsigned char)*sz); Base64Encode(buf64,bufchar);//Convert to Base64 code. dest=buf64; //Get base64 code //............................................ // Delete pointers and return: //............................................ if(bufchar) delete [] bufchar; if(buf64) delete [] buf64; return dest; } //---------------------------------------- // 对CString字符串进行base64解码: // 解码后字符串变短大约1/4: //---------------------------------------- inline CString StringBase64Decode(CString& base64code) { CStringdest; unsigned char * buf64=0, * bufu8=0; wchar_t * bufchar=0; UINT sz; int u8len; //............................................ //Convert base64 code from Unicode to char: //............................................ buf64=CString2Char(base64code,(int&)u8len); if(buf64==0) { delete [] buf64; return L\"\"; } //............................................ //Decode base64 code, we obtain string in // UTF-8 format: //............................................ bufu8=new unsigned char[u8len*2]; //When decoding, string size will decrease, //therefore size of bufu8 is the same as //that of buf64. memset(bufu8,0,sizeof(unsigned char)*u8len*2); Base64Decode(bufu8,buf64,u8len); //............................................ // Convert UTF-8 to original text (Unicode): //............................................ //A. Get buffer size when converted to text: sz=MultiByteToWideChar(CP_UTF8,0,(char *)bufu8,u8len,NULL,0); //B. Decode string to original text: bufchar=new wchar_t[sz]; memset(bufchar,0,sizeof(wchar_t)*sz); MultiByteToWideChar(CP_UTF8,0,(char *)bufu8,u8len,bufchar,sz); dest=bufchar;//Get original text if(buf64) delete [] buf64; if(bufu8) delete [] bufu8; if(bufchar) delete [] bufchar; return dest; } //************************************************************************************* // Base64编码命名空间结束 //************************************************************************************* }; #endif // #ifndef _BASE64_INCLUDE__H__ #include class ZBase64 { public: /*编码 DataByte [in]输入的数据长度,以字节为单位 */ string Encode(const unsigned char* Data,intDataByte); /*解码 DataByte [in]输入的数据长度,以字节为单位 OutByte [out]输出的数据长度,以字节为单位,请不要通过返回值计算 输出数据的长度 */ string Decode(const char* Data,intDataByte,int&OutByte); }; #include \"stdAfx.h\" #include \"ZBase64.h\" string ZBase64::Encode(const unsigned char* Data,intDataByte) { //编码表 const char EncodeTable[]=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"; //返回值 string strEncode; unsigned char Tmp[4]={0}; intLineLength=0; for(inti=0;i<(int)(DataByte / 3);i++) { Tmp[1] = *Data++; Tmp[2] = *Data++; Tmp[3] = *Data++; strEncode+= EncodeTable[Tmp[1] >> 2]; strEncode+= EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F]; strEncode+= EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F]; strEncode+= EncodeTable[Tmp[3] & 0x3F]; if(LineLength+=4,LineLength==76) {strEncode+=\"\\r\\n\";LineLength=0;} } //对剩余数据进行编码 int Mod=DataByte % 3; if(Mod==1) { Tmp[1] = *Data++; strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4)]; strEncode+= \"==\"; } else if(Mod==2) { Tmp[1] = *Data++; Tmp[2] = *Data++; strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)]; strEncode+= EncodeTable[((Tmp[2] & 0x0F) << 2)]; strEncode+= \"=\"; } return strEncode; } string ZBase64::Decode(const char* Data,intDataByte,int&OutByte) { //解码表 const char DecodeTable[] = { , 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, , // '/' , 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9' , 0, 0, 0, 0, 0, 0, , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, , 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z' , 0, 0, 0, 0, 0, , 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, , 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z' }; //返回值 string strDecode; intnValue; inti= 0; while (i nValue = DecodeTable[*Data++] << 18; nValue += DecodeTable[*Data++] << 12; strDecode+=(nValue& 0x00FF0000) >> 16; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++] << 6; strDecode+=(nValue& 0x0000FF00) >> 8; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++]; strDecode+=nValue& 0x000000FF; OutByte++; } } i += 4; } else// 回车换行,跳过 { Data++; i++; } } return strDecode; } CStringCScanDlg::EncodeImage() {//对图片进行Base64编码 ZBase64 zBase; //图片编码 CxImage image; // 定义一个CxImage对象 image.Load(this->m_strImgPath, CXIMAGE_FORMAT_JPG); 类型 long size=0;//得到图像大小 BYTE* buffer=0;//存储图像数据的缓冲 //先装载jpg文件,需要指定文件 image.Encode(buffer,size,CXIMAGE_FORMAT_JPG);//把image对象中的图像以type类型数据copy到buffer string strTmpResult=zBase.Encode(buffer,size); CString result; result = strTmpResult.c_str(); return result; } void CScanDlg::DecodeImageData(CStringstrData) {//对Base64编码过的数据解码并显示原图片 ZBase64 zBase; intOutByte=0; string strTmpResult=zBase.Decode(strData,strData.GetLength(),OutByte); inti,len = strTmpResult.length(); BYTE *buffer = new BYTE[len]; for (i=0;i buffer[i] = strTmpResult[i]; } CxImage image(buffer,len,CXIMAGE_FORMAT_JPG);//把内存缓冲buffer中的数据构造成Image对象 delete [] buffer; CDC* hdc = m_picture.GetDC(); m_bitmap = image.MakeBitmap(hdc->m_hDC); HBITMAP h0ldBmp = m_picture.SetBitmap(m_bitmap); if(h0ldBmp) DeleteObject(h0ldBmp); if(hdc->m_hDC) m_picture.ReleaseDC(hdc); if(m_bitmap) DeleteObject(m_bitmap); } #ifndef ___BASE64_H___ #define ___BASE64_H___ #include public: CBase64(); ~CBase64(); bool static Encode(const unsigned char *pIn, unsigned long uInLen, string&strOut); bool static Encode(const unsigned char *pIn, unsigned long uInLen, unsigned char *pOut, unsigned long *uOutLen); bool static Decode(const string&strIn, unsigned char *pOut, unsigned long *uOutLen) ; bool static Decode(const unsigned char *pIn, unsigned long uInLen, unsigned char *pOut, unsigned long *uOutLen) ; }; #endif // ___BASE64_H___ #include \"StdAfx.h\" #include \"CBase64.h\" static const char *g_pCodes = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"; static const unsigned char g_pMap[256] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 254, 255, 255, 255, 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, 255, 255, 255, 255, 255, 255, 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, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; CBase64::CBase64() { } CBase64::~CBase64() { } bool CBase64::Encode(const unsigned char *pIn, unsigned long uInLen, unsigned char *pOut, unsigned long *uOutLen) { unsigned long i, len2, leven; unsigned char *p; if(pOut == NULL || *uOutLen == 0) return false; //ASSERT((pIn != NULL) && (uInLen != 0) && (pOut != NULL) && (uOutLen != NULL)); len2 = ((uInLen + 2) / 3) << 2; if((*uOutLen) < (len2 + 1)) return false; p = pOut; leven = 3 * (uInLen / 3); for(i = 0; i *p++ = g_pCodes[((pIn[0] & 3) << 4) + (pIn[1] >> 4)]; *p++ = g_pCodes[((pIn[1] & 0xf) << 2) + (pIn[2] >> 6)]; *p++ = g_pCodes[pIn[2] & 0x3f]; pIn += 3; } if (i unsigned char b = ((i + 1) *p++ = g_pCodes[((a & 3) << 4) + (b >> 4)]; *p++ = ((i + 1) *p = 0; // Append NULL byte *uOutLen = p - pOut; return true; } bool CBase64::Encode(const unsigned char *pIn, unsigned long uInLen, string&strOut) { unsigned long i, len2, leven; strOut = \"\"; //ASSERT((pIn != NULL) && (uInLen != 0) && (pOut != NULL) && (uOutLen != NULL)); len2 = ((uInLen + 2) / 3) << 2; //if((*uOutLen) < (len2 + 1)) return false; //p = pOut; leven = 3 * (uInLen / 3); for(i = 0; i strOut += g_pCodes[((pIn[0] & 3) << 4) + (pIn[1] >> 4)]; strOut += g_pCodes[((pIn[1] & 0xf) << 2) + (pIn[2] >> 6)]; strOut += g_pCodes[pIn[2] & 0x3f]; pIn += 3; } if (i unsigned char a = pIn[0]; unsigned char b = ((i + 1) strOut += g_pCodes[((a & 3) << 4) + (b >> 4)]; strOut += ((i + 1) //*p = 0; // Append NULL byte //*uOutLen = p - pOut; return true; } bool CBase64::Decode(const string&strIn, unsigned char *pOut, unsigned long *uOutLen) { unsigned long t, x, y, z; unsigned char c; unsigned long g = 3; //ASSERT((pIn != NULL) && (uInLen != 0) && (pOut != NULL) && (uOutLen != NULL)); for(x = y = z = t = 0; x if((z + g) > *uOutLen) { return false; } // Buffer overflow pOut[z++] = (unsigned char)((t>>16)&255); if(g > 1) pOut[z++] = (unsigned char)((t>>8)&255); if(g > 2) pOut[z++] = (unsigned char)(t&255); y = t = 0; } } *uOutLen = z; return true; } // BASE64.cpp : Defines the entry point for the console application. // #include \"stdafx.h\" #include \"CBase64.h\" #include int main(intargc, char* argv[]) { unsigned long len = 10; unsigned char pIn[100]; unsigned char pOut[100]; memcpy(pIn,\"你好\ string strout; cout<<(char*)pIn< if(CBase64::Decode(stroIn, pOut, &len)) { cout<<(char *)pOut< 因篇幅问题不能全部显示,请点此查看更多更全内容