-
Notifications
You must be signed in to change notification settings - Fork 0
/
FEAL.java
119 lines (91 loc) · 3.08 KB
/
FEAL.java
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
*/
import java.util.Arrays;
import java.lang.Byte;
public class FEAL {
static int rounds = 4;
static byte rot2(byte x) {
return (byte)(((x&255)<<2)|((x&255)>>>6));
}
static byte g0(byte a,byte b) {
return rot2((byte)((a+b)&255));
}
static byte g1(byte a,byte b) {
return rot2((byte)((a+b+1)&255));
}
static int pack(byte[] b,int startindex) {
/* pack 4 bytes into a 32-bit Word */
return ((b[startindex+3]&255) |((b[startindex+2]&255)<<8)|((b[startindex+1]&255)<<16)|((b[startindex]&255)<<24));
}
static void unpack(int a,byte[] b,int startindex) {
/* unpack bytes from a 32-bit word */
b[startindex]=(byte)(a>>>24);
b[startindex+1]=(byte)(a>>>16);
b[startindex+2]=(byte)(a>>>8);
b[startindex+3]=(byte)a;
}
static int f(int input) {
byte[] x = new byte[4];
byte[] y = new byte[4];
unpack(input,x,0);
y[1]=g1((byte)((x[0]^x[1])&255),(byte)((x[2]^x[3])&255));
y[0]=g0((byte)(x[0]&255),(byte)(y[1]&255));
y[2]=g0((byte)(y[1]&255),(byte)((x[2]^x[3])&255));
y[3]=g1((byte)(y[2]&255),(byte)(x[3]&255));
return pack(y,0);
}
static void encrypt(byte data[],int key[]) {
int left,right,temp;
left=pack(data,0);
right=left^pack(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];
unpack(left,data,0);
unpack(right,data,4);
}
static void decrypt(byte data[],int key[]) {
int left,right,temp;
right=pack(data,0)^key[4];
left=right^pack(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;
unpack(left,data,0);
unpack(right,data,4);
}
public static void main(String args[]) {
byte[] data = new byte[8];
/* Not the keys you are looking for!!! */
int key[]={0x0,0x0,0x0,0x0,0x0,0x0};
if (args.length!=8) {
System.out.println("command line error - input 8 bytes of plaintext in hex");
System.out.println("For example:");
System.out.println("java FEAL 01 23 45 67 89 ab cd ef");
return;
}
for (int i=0;i<8;i++)
data[i] = (byte)(Integer.parseInt(args[i],16)&255);
System.out.print("Plaintext= ");
for (int i=0;i<8;i++) System.out.printf("%02x",data[i]);
System.out.print("\n");
encrypt(data,key);
System.out.print("Ciphertext= ");
for (int i=0;i<8;i++) System.out.printf("%02x",data[i]);
System.out.print("\n");
decrypt(data,key);
System.out.print("Plaintext= ");
for (int i=0;i<8;i++) System.out.printf("%02x",data[i]);
System.out.print("\n");
return;
}
}