#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define num_rounds 32
void encipher(unsigned int v[2], unsigned int key[4])
{
unsigned int i;
unsigned int v0 = v[0];
unsigned int v1 = v[1];
unsigned int sum = 0;
unsigned int delta = 0x9E3779B9;
for ( 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 i;
unsigned v0 = v[0];
unsigned v1 = v[1];
unsigned delta = 0x9E3779B9;
unsigned sum = delta * num_rounds;
for (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 != 5)
{
printf("\n Usage:%s e(encipher) password sourcefile outFile \n",argv[0]);
printf("\n Usage:%s d(decipher) password sourcefule outfile \n", argv[0]);
return 0;
}
for (int i = 0; i < 5; i++)
{
printf("第%d个参数是:%s \n", i, argv[i]);
}
char password[100] = { 0 };
strcpy_s(password, argv[2]);
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);
return 0;
}
在写这个TEA实现的过程中,因为自己对C语言的知识点掌握不牢固,多次使用都未能实现效果。例如:模加运算的理解,十六进制数的取值。 视频演示
|