BASE64加密算法

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值