前一阵子,自己想了个较容易实现的算法,不知道可靠不可靠,特在此贴出来各位帮忙参考参考。
1)我想到3种简单的运算可以在字节的级别上可逆,他们是+,-,^,逆运算分别是-,+,^
2)对每一个字节假如是由一个数对其执行了一个运算,那么我们只要用同一个数对其执行逆运算就可以恢复了
3)用0表示'+',1表示'-',2表示'^'
4)加密开始时随机生成一个32byte密钥(也可以是(64,128....)
5)把该密钥转化成3进制的数组,每一个字节可以化为3进制表示的,固定长度为6位(3^5=243最接近255了),比如8表示为E{0,0,0,0,2,2},那么32字节的密钥可以
转化为长度为6*32=192的数组了
6)现在加密开始,输入一个串,该算法一个字节一个字节的加密,假如是第N个字节,那么可以通过N%32取得加密的操作数,同时通过N%192取得当前操作符(0或则1或则2)
下面给出C版的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tag_YCODEC
{
unsigned char key[32];
char ops[192];
void (*encrypt)(struct tag_YCODEC *codec, unsigned char *bytes,int off,int len);
void (*decrypt)(struct tag_YCODEC *codec, unsigned char *bytes,int off,int len);
}YCodec;
static void YCodec_encrypt(YCodec *ycodec, unsigned char *bytes,int off,int len);
static void YCodec_decrypt(YCodec *ycodec, unsigned char *bytes,int off,int len);
static void Init_YCodec(YCodec *ycodec,unsigned char *theKey)
{
int i;
//TODO make sure no buffer-overflow
memcpy(ycodec->key,theKey,32);
memset(ycodec->ops,0,192);
for(i=0;i<32;i++)
{
int k=ycodec->key[i];
int j=(i+1)*6;
while(k>0)
{
ycodec->ops[--j]=k%3;
k=(k-ycodec->ops[j])/3;
}
}
ycodec->encrypt=&YCodec_encrypt;
ycodec->decrypt=&YCodec_decrypt;
}
static void YCodec_encrypt(YCodec *ycodec, unsigned char *bytes,int off,int len)
{
int idx=off;
for(;idx<off+len;idx++)
{
if(ycodec->ops[idx%192]==0)//'+'
{
bytes[idx]+=ycodec->key[idx%32];
}
else if(ycodec->ops[idx%192]==1)//'-'
{
bytes[idx]-=ycodec->key[idx%32];
}
else if(ycodec->ops[idx%192]==2)//'^'
{
bytes[idx]^=ycodec->key[idx%32];
}
else
{
//error
}
}
}
static void YCodec_decrypt(YCodec *ycodec, unsigned char *bytes,int off,int len)
{
int idx=off;
for(;idx<off+len;idx++)
{
if(ycodec->ops[idx%192]==0)//'-'
{
bytes[idx]-=ycodec->key[idx%32];
}
else if(ycodec->ops[idx%192]==1)//'+'
{
bytes[idx]+=ycodec->key[idx%32];
}
else if(ycodec->ops[idx%192]==2)//'^'
{
bytes[idx]^=ycodec->key[idx%32];
}
else
{
//error
}
}
}
int main(char *argv[],int argc)
{
char key[]="01234567890123456789012345678901";
char text[]="hello, this is a test string ererrergfhfghgfffhfghfvvdfgsrtereretrtdddsdfghhjjkjklkkldfdfdfdfdfdf toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
.";
YCodec ycodec;
Init_YCodec(&ycodec,(unsigned char *)key);
ycodec.encrypt(&ycodec,(unsigned char *)text,0,sizeof(text)-1);
printf("after encrypt :%s\n",text);
ycodec.decrypt(&ycodec,(unsigned char *)text,0,sizeof(text)-1);
printf("after decrypt :%s\n",text);
return 0;
}