相同的key每一次加密的密文都不一样.难于破解.整个密文相关.修改其中一段后,以后的数据解密不正确
typedef unsigned int Unit;
std::string encrypt(const std::string &src,Unit key)
{
Unit seed = 0;
const size_t unitlen = sizeof(Unit);
size_t len = (src.length() + unitlen-1) & ~(unitlen-1);
Unit *srcdata = (Unit*)malloc(len);
bzero(srcdata,len);
memcpy(srcdata,src.data(),src.size());
std::string dest;
int i = 0;
srand(time(NULL));
seed = rand()%0xFFFF;
dest.append((char*)&seed,sizeof(Unit));
do
{
seed = *(srcdata+i) ^ seed ^ key;
dest.append((char*)&seed,unitlen);
i++;
}while(i<len/unitlen);
free(srcdata);
return dest;
}
std::string dencrypt(const std::string &src, Unit key)
{
Unit seed = 0;
Unit *srcData = NULL;
std::string dest;
const size_t unitlen = sizeof(Unit);
srcData = (Unit*)src.data();
seed = *((Unit*)srcData);
int i = 1;
while(i<src.size()/unitlen)
{
seed = *(srcData + i) ^ key ^ seed;
dest.append((char*)&seed,unitlen);
seed = *(srcData + i);
i++;
}
return dest;
}