一种加密,解密的思路
程序员文章站
2022-06-09 22:00:34
...
加密的一种思路:
1. 客户端有个初始key,这个key先加密(异或)4个字节内容,生成4个字节的密文
2. 根据4个字节的密文,算法产生新key2, 使用key2解密下一段 4个字节的内容, 以此类推
对应的解密:
1. 服务器本身知道初始key
2. 服务器先根据4个字节的密文,使用客户端相同的算法产生key2
3. 使用key 解密第一段4个字节
4.以此类推, 使用key2解密第二段密文
#include <stdio.h>
#define WORD unsigned short
#define DWORD unsigned int
DWORD g_dwPacketKey = 666;
WORD SeedRandMap(WORD wSeed)
{
DWORD dwHold = wSeed;
return (WORD)((dwHold = dwHold * 244403L + 2543301L) >> 16);
}
int main()
{
//原文
unsigned char data[8] = { 1,2,3,4,5,6,7,8};
//加密一段内容
{
DWORD * pdw = (DWORD *)data;
WORD * pSe = (WORD *)data;
DWORD Key = 111; //初始秘钥
for (int i = 0; i < 2; i++)
{
//加密四个字节
*pdw++ ^= Key;
//根据前面四个字节密文 生成新Key2
DWORD Key2 = ((DWORD)SeedRandMap(*pSe++)) << 16;
Key2 |= SeedRandMap(*pSe++);
Key2 ^= g_dwPacketKey;
Key = Key2;
}
for (size_t i = 0; i < 8; i++)
{
printf("%x ", data[i]);
}
printf("\n");
}
/////////////////////////////////////////////////////////
//解密一段
{
DWORD * pdw = (DWORD *)data;
WORD * pSe = (WORD *)data;
DWORD Key = 111; //初始秘钥
for (int i = 0; i < 2; i++)
{
//解密前,先根据密文获取下一个解密的Key2
DWORD Key2 = ((DWORD)SeedRandMap(*pSe++)) << 16;
Key2 |= SeedRandMap(*pSe++);
Key2 ^= g_dwPacketKey;
//解密四个字节
*pdw++ ^= Key;
Key = Key2;
}
for (size_t i = 0; i < 8; i++)
{
printf("%x ", data[i]);
}
printf("\n");
}
}
上一篇: Linux命令集合一