#include "stdafx.h"
// 常量
#define C1 52845
#define C2 22719
CString Encrypt(CString csDeCode, WORD Key) // 加密函数
{
CString Result,str;
int i,j;
Result=csDeCode; // 初始化结果字符串
for(i=0; i<csDeCode.GetLength(); i++) // 依次对字符串中各字符进行操作
{
Result.SetAt(i, csDeCode.GetAt(i)^(Key>>8)); // 将密钥移位后与字符异或
Key = ((BYTE)Result.GetAt(i)+Key)*C1+C2; // 产生下一个密钥
}
csDeCode=Result; // 保存结果
Result.Empty(); // 清除结果
for(i=0; i<csDeCode.GetLength(); i++) // 对加密结果进行转换
{
j=(BYTE)csDeCode.GetAt(i); // 提取字符
// 将字符转换为两个字母保存
str="12"; // 设置str长度为2
str.SetAt(0, 65+j/26);//这里将65改大点的数例如256,密文就会变乱码,效果更好,相应的,解密处要改为相同的数
str.SetAt(1, 65+j%26);
Result += str;
}
return Result;
}
CString Decrypt(CString csEnCode, WORD Key) // 解密函数
{
CString Result,str;
int i,j;
Result.Empty(); // 清除结果
for(i=0; i < csEnCode.GetLength()/2; i++) // 将字符串两个字母一组进行处理
{
j = ((BYTE)csEnCode.GetAt(2*i)-65)*26;//相应的,解密处要改为相同的数
j += (BYTE)csEnCode.GetAt(2*i+1)-65;
str="1"; // 设置str长度为1
str.SetAt(0, j);
Result+=str; // 追加字符,还原字符串
}
csEnCode = Result;
// 保存中间结果
for(i=0; i<csEnCode.GetLength(); i++)
// 依次对字符串中各字符进行操作
{
Result.SetAt(i, (BYTE)csEnCode.GetAt(i)^(Key>>8)); // 将密钥移位后与字符异或
Key = ((BYTE)csEnCode.GetAt(i)+Key)*C1+C2; // 产生下一个密钥
}
return Result;
}
用法:
CString text=_T("192.168.18.14");//需要加密的字符串
WORD key=1314;//key
CString jiami=Encrypt(text,key);//加密
AfxMessageBox(_T("密文:")+jiami);
CString jiemi=Decrypt(jiami,key);//解密
AfxMessageBox(_T("原文:")+jiemi);
WORD key=1314;//key
CString jiami=Encrypt(text,key);//加密
AfxMessageBox(_T("密文:")+jiami);
CString jiemi=Decrypt(jiami,key);//解密
AfxMessageBox(_T("原文:")+jiemi);
转自:http://blog.csdn.net/yaoohfox/archive/2009/07/17/4357325.aspx