最近在写小玩意,用到了base64编码,但是考虑到体积大小,网上的多种实现都是利用开源的代码,这就增加了其大小。我想win api能不能实现base64编码、解码。通过一通乱搜,,还有收获。就有了以下代码
#pragma comment(lib,"crypt32.lib") LPSTR Base64Encode(LPBYTE lpBuffer,DWORD dwLen) { DWORD dwNeed; LPSTR lpBase64Str ; DWORD dwIndex ; DWORD dwIndexJ; dwNeed = 0; lpBase64Str = NULL ; CryptBinaryToStringA(lpBuffer,dwLen,CRYPT_STRING_BASE64,NULL,&dwNeed); if (dwNeed) { lpBase64Str = (LPSTR)malloc(dwNeed); ZeroMemory(lpBase64Str,dwNeed); CryptBinaryToStringA(lpBuffer,dwLen,CRYPT_STRING_BASE64,lpBase64Str,&dwNeed); dwIndex = 0; while(*(lpBase64Str+dwIndex)!=0) { if (*(lpBase64Str+dwIndex) == 0x0d || *(lpBase64Str+dwIndex)==0x0a) { dwIndexJ = dwIndex +1; while (*(lpBase64Str+dwIndexJ)!=0) { *(lpBase64Str+dwIndexJ-1)= *(lpBase64Str+dwIndexJ); dwIndexJ ++ ; } *(lpBase64Str+dwIndexJ-1) = 0 ; }else { dwIndex ++ ; } } } return lpBase64Str ; } LPBYTE Base64Decode(LPSTR lpBase64Str,LPDWORD lpdwLen) { DWORD dwLen ; DWORD dwNeed ; LPBYTE lpBuffer ; dwLen = strlen(lpBase64Str); dwNeed = 0; CryptStringToBinaryA(lpBase64Str,0,CRYPT_STRING_BASE64,NULL,&dwNeed,NULL,NULL); if (dwNeed) { lpBuffer = (LPBYTE)malloc(dwNeed); CryptStringToBinaryA(lpBase64Str,0,CRYPT_STRING_BASE64,lpBuffer,&dwNeed,NULL,NULL); *lpdwLen = dwNeed ; } return lpBuffer ; }
仅供参考
win api 实现 base64编码、解码