在安全學領域,TEA(Tiny Encryption Algorithm)是一種分組,它的實現非常簡單,通常只需要很精短的幾行代碼。TEA 算法最初是由劍橋計算機實驗室的 David Wheeler 和 Roger Needham 在 1994 年設計的。
以下是TEA算法C++實現(於4月21日改進了參數的設置)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<conio.h>
#include<unistd.h>
#define num_rounds 32
using namespace std;
void encipher(unsigned int v[2],unsigned int key[4])
{
unsigned int v0=v[0],v1=v[1],sum=0,delta=0x9E3779B9;
for(int i=0;i<num_rounds;i++)
{
v0+=(((v1<<4)^(v1>>5))+v1)^(sum+key[sum&3]);
sum+=delta;
v1+=(((v0<<4)^(v0>>5))+v0)^(sum+key[(sum>>11)&3]);
}
v[0]=v0;
v[1]=v1;
}
void decipher(unsigned int v[2],unsigned int key[4])
{
unsigned int v0=v[0],v1=v[1],delta=0x9E3779B9,sum=delta*num_rounds;
for(int i=0;i<num_rounds;i++)
{
v1-=(((v0<<4)^(v0>>5))+v0)^(sum+key[(sum>>11)&3]);
sum-=delta;
v0-=(((v1<<4)^(v1>>5))+v1)^(sum+key[sum&3]);
}
v[0]=v0;
v[1]=v1;
}
int main(int argc,char *argv[])
{
if(argc!=4&&argc!=5)
{
cout<<endl<<"Usage: e(encipher) password sourceFileName outFileName"<<endl;
cout<<endl<<"Usage: d(decipher) password sourceFileName outFileName"<<endl;
return 0;
}
char password[100]={0};
strcpy(password,argv[2]);
if(argc==4)
{
FILE *fpin=fopen(argv[3],"rb");
FILE *fpout=fopen("temporary","wb+");
if(fpin!=NULL&&fpout!=NULL)
{
while(!feof(fpin))
{
unsigned int msg[2];
msg[0]=msg[1]=0;
if(fread(msg,1,8,fpin)==0)
break;
if(argv[1][0]=='e')
encipher(msg,(unsigned int*)password);
else
decipher(msg,(unsigned int*)password);
fwrite(msg,1,8,fpout);
}
fclose(fpin);
fclose(fpout);
}
unlink(argv[3]);
rename("temporary",argv[3]);
}
else
{
FILE *fpin=fopen(argv[3],"rb");
FILE *fpout=fopen(argv[4],"wb");
if(fpin!=NULL&&fpout!=NULL)
{
while(!feof(fpin))
{
unsigned int msg[2];
msg[0]=msg[1]=0;
if(fread(msg,1,8,fpin)==0)
break;
if(argv[1][0]=='e')
encipher(msg,(unsigned int*)password);
else
decipher(msg,(unsigned int*)password);
fwrite(msg,1,8,fpout);
}
fclose(fpin);
fclose(fpout);
}
}
}
代碼在cmd下使用需要傳入5個參數,分別是
.exe的名稱、e或d(傳入不是e的時候默認解密)、加密\解密密碼、源文件、目標文件
注意!!
源文件和目標文件不能是同一個文件,否則會造成文件的丟失
TEA算法可以應用在bat腳本下,用於文件的加密和防護。
—————————————————————————————————————————————
4月21日
源代碼修正,適用於4個參數與5個參數的情況
4個參數即( 程序名 運行方式 密碼 源文件)此時源文件即目標文件,TEA.exe將直接對密源文件內容加密,加密後的內容也存儲在源文件中,省去了bat下刪除和重命名的麻煩。
缺點是無法直接對加密後的文件修改類型(當然bat批處理後這些都不是問題)