- 论坛徽章:
- 0
|
给你base64
的C版本
- /*ChinaDream */
- #include <stdio.h>
- char *B64ENC(char *pszIn,char *pszOut,int iLen)
- {
- const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- unsigned char CDE[3];
- if(iLen > 0)
- {
- if(iLen > 3)
- {
- iLen = 3;
- }
-
- memcpy(CDE,pszIn,iLen);
- pszOut[0] = cb64[ CDE[0] >> 2 ];
- pszOut[1] = cb64[ ((CDE[0] & 0x03) << 4) | ((CDE[1] & 0xf0) >> 4) ];
- if(iLen > 1)
- {
- pszOut[2] = cb64[ ((CDE[1] & 0x0f) << 2) | ((CDE[2] & 0xc0) >> 6) ];
- }
- else
- {
- pszOut[2] = '=';
- }
-
- if(iLen > 2)
- {
- pszOut[3] = cb64[ CDE[2] & 0x3f ];
- }
- else
- {
- pszOut[3] = '=';
- }
- }
- return (pszOut);
- }
- char *B64DEC(char *pszIn,char *pszOut)
- {
- const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
- unsigned char CDE[4];
- memcpy(CDE,pszIn,4);
- if ((CDE[0] != '=') && (CDE[1] != '='))
- {
- CDE[0] = cd64[CDE[0] - 43] - 62;
- CDE[1] = cd64[CDE[1] - 43] - 62;
- pszOut[0] = CDE[0] << 2 | CDE[1] >> 4;
- if (CDE[2] != '=')
- {
- CDE[2] = cd64[CDE[2] - 43] - 62;
- pszOut[1] = CDE[1] << 4 | CDE[2] >> 2;
- if (CDE[3] != '=')
- {
- CDE[3] = cd64[CDE[3] - 43] - 62;
- pszOut[2] = ((CDE[2] << 6) & 0xc0) | CDE[3];
- }
- else
- {
- pszOut[2]=0;
- }
- }
- else
- {
- pszOut[1]=0;
- }
- }
- return (pszOut);
- }
- char *B64ENCCODE(char *pszIn,char *pszOut,int iLen)
- {
- int i;
- int iDIV;
- int iMOD;
- char *pszSrc;
- char *pszDes;
- pszSrc = pszIn;
- pszDes = pszOut;
- iDIV = (iLen / 3);
- iMOD = (iLen % 3);
- for(i=0;i<iDIV;i++)
- {
- B64ENC(pszSrc,pszDes,3);
- pszSrc+=3;
- pszDes+=4;
- }
- if(iMOD >0)
- {
- B64ENC(pszSrc,pszDes,iMOD);
- pszSrc+=3;
- pszDes+=4;
- }
- *pszDes = 0;
- return (pszOut);
- }
- char *B64DECCODE(char *pszIn,char *pszOut,int iLen)
- {
- int i;
- int iDIV;
- char *pszSrc;
- char *pszDes;
- pszSrc = pszIn;
- pszDes = pszOut;
- iDIV = (iLen / 4);
- for(i=0;i<iDIV;i++)
- {
- B64DEC(pszSrc,pszDes);
- pszSrc+=4;
- pszDes+=3;
- }
- *pszDes = 0;
- return (pszOut);
- }
- /*
- void main()
- {
- char In[]="用C对BASE64加密实现!太烦了!!!!!测试!!!!!!";
- char Out[2048]={0};
- char Tmp[128]={0};
- B64ENCCODE(In,Out,strlen(In));
- printf("ENCCODE=%s\n",Out);
- B64DECCODE(Out,Tmp,strlen(Out));
- printf("DECCODE=%s\n",Tmp);
- }
- */
复制代码 |
|