-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFEAL.c
More file actions
119 lines (91 loc) · 2.26 KB
/
Copy pathFEAL.c
File metadata and controls
119 lines (91 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* The FEAL cipher
*/
#include <stdio.h>
#define WORD32 unsigned int
#define BYTE unsigned char
#define ROUNDS 4
#define ROT2(x) (((x)<<2) | ((x)>>6))
#define G0(a,b) (ROT2((BYTE)((a)+(b))))
#define G1(a,b) (ROT2((BYTE)((a)+(b)+1)))
static WORD32 pack32(BYTE *b)
{ /* pack 4 bytes into a 32-bit Word */
return (WORD32)b[3]|((WORD32)b[2]<<8)|((WORD32)b[1]<<16)|((WORD32)b[0]<<24);
}
static void unpack32(WORD32 a,BYTE *b)
{ /* unpack bytes from a 32-bit word */
b[0]=(BYTE)(a>>24);
b[1]=(BYTE)(a>>16);
b[2]=(BYTE)(a>>8);
b[3]=(BYTE)a;
}
WORD32 f(WORD32 input)
{
BYTE x[4],y[4];
unpack32(input,x);
y[1]=G1(x[1]^x[0],x[2]^x[3]);
y[0]=G0(x[0],y[1]);
y[2]=G0(y[1],x[2]^x[3]);
y[3]=G1(y[2],x[3]);
return pack32(y);
}
void encrypt(BYTE data[8],WORD32 key[6])
{
WORD32 left,right,temp;
left=pack32(&data[0]);
right=left^pack32(&data[4]);
for (int i=0;i<ROUNDS;i++)
{
temp=right;
right=left^f(right^key[i]);
left=temp;
}
temp=left;
left=right^key[4];
right=temp^right^key[5];
unpack32(left,&data[0]);
unpack32(right,&data[4]);
}
void decrypt(BYTE data[8],WORD32 key[6])
{
WORD32 left,right,temp;
right=pack32(&data[0])^key[4];
left=right^pack32(&data[4])^key[5];
for (int i=0;i<ROUNDS;i++)
{
temp=left;
left=right^f(left^key[ROUNDS-1-i]);
right=temp;
}
right^=left;
unpack32(left,&data[0]);
unpack32(right,&data[4]);
}
/* Not the key you are looking for!!! */
WORD32 key[6]={0x0,0x0,0x0,0x0,0x0,0x0};
int main(int argc,char **argv)
{
BYTE data[8];
argc--; argv++;
if (argc!=8)
{
printf("command line error - input 8 bytes of plaintext in hex\n");
printf("For example:-\n");
printf("feal 01 23 45 67 89 ab cd ef\n");
return 0;
}
for (int i=0;i<8;i++)
sscanf(argv[i],"%hhx",&data[i]);
printf("Plaintext= ");
for (int i=0;i<8;i++) printf("%02x",data[i]);
printf("\n");
encrypt(data,key);
printf("Ciphertext= ");
for (int i=0;i<8;i++) printf("%02x",data[i]);
printf("\n");
decrypt(data,key);
printf("Plaintext= ");
for (int i=0;i<8;i++) printf("%02x",data[i]);
printf("\n");
return 0;
}