#include <stdio.h>
#include <windows.h>
char Chars[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890+=";
int GetIndex(BYTE b)
{
for (int i = 0; i < 64; i++)
{
if (b == Chars[i])
{
return i;
}
}
return 0;
}
VOID Base64Encrypt(BYTE* pScr, int nScrLen, BYTE* pDes, int& nDesLen)
{
int nCount = nScrLen / 3;
int i;
for (i = 0; i < nCount; i++)
{
pDes[i * 4] = Chars[(pScr[3 * i] & 252) >> 2];
pDes[i * 4 + 1] = Chars[((pScr[3 * i] & 3) << 4) + ((pScr[3 * i + 1] & 240) >> 4)];
pDes[i * 4 + 2] = Chars[((pScr[3 * i + 1] & 15) << 2) + ((pScr[3 * i + 2] & 192) >> 6)];
pDes[i * 4 + 3] = Chars[pScr[3 * i + 2] & 63];
}
nDesLen = nCount * 4;
nCount = nScrLen % 3;
if (nCount == 1)
{
pDes[i * 4] = Chars[(pScr[3 * i] & 252) >> 2];
pDes[i * 4 + 1] = Chars[((pScr[3 * i] & 3) << 4)];
nDesLen += 2;
}
else if (nCount == 2)
{
pDes[i * 4] = Chars[(pScr[3 * i] & 252) >> 2];
pDes[i * 4 + 1] = Chars[((pScr[3 * i] & 3) << 4) + ((pScr[3 * i + 1] & 240) >> 4)];
pDes[i * 4 + 2] = Chars[((pScr[3 * i + 1] & 15) << 2)];
nDesLen += 3;
}
}
VOID Base64Decrypt(BYTE* pScr, int nScrLen, BYTE* pDes, int& nDesLen)
{
int nCount = nScrLen / 4;
int i;
for (i = 0; i < nCount; i++)
{
pDes[i * 3] = (GetIndex(pScr[i * 4]) << 2) + (GetIndex(pScr[i * 4 + 1]) >> 4);
pDes[i * 3 + 1] = ((GetIndex(pScr[i * 4 + 1]) & 15) << 4) + (GetIndex(pScr[i * 4 + 2]) >> 2);
pDes[i * 3 + 2] = ((GetIndex(pScr[i * 4 + 2]) & 3) << 6) + (GetIndex(pScr[i * 4 + 3]));
}
nDesLen = 3 * nCount;
if (nScrLen % 4 == 2)
{
pDes[i * 3] = (GetIndex(pScr[i * 4]) << 2) + (GetIndex(pScr[i * 4 + 1]) >> 4);
nDesLen++;
}
else if (nScrLen % 4 == 3)
{
pDes[i * 3] = (GetIndex(pScr[i * 4]) << 2) + (GetIndex(pScr[i * 4 + 1]) >> 4);
pDes[i * 3 + 1] = ((GetIndex(pScr[i * 4 + 1]) & 15) << 4) + (GetIndex(pScr[i * 4 + 2]) >> 2);
nDesLen += 2;
}
}
int main(void)
{
BYTE buff1[24] = { 0 };
BYTE buff2[24] = { 0 };
int nLen1 = 0;
int nLen2 = 0;
BYTE Str[] = "Hello a World";
Base64Encrypt(Str, sizeof(Str), buff1, nLen1);
Base64Decrypt(buff1, nLen1, buff2, nLen2);
return 0;
}
BASE64加密算法
最新推荐文章于 2024-04-17 03:49:17 发布