-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cipher.h
88 lines (71 loc) · 2.31 KB
/
Cipher.h
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
// Nb = 4 words(16 bytes/unsigned chars).
// Number of columns (32-bit words) comprising the State.
// Nr = 10
// Number of rounds.
// Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
void Cipher(unsigned char in[16], unsigned char out[16], unsigned char w[176])
{
// We encrypt in blocks. Copy the content of the first 16 blocks to our state variable
unsigned char state[16];
unsigned char temp_w[16];
// state = in
for (int i = 0; i < 16; i++) {
state[i] = in[i];
}
for (int i = 0; i < 16; i++) {
temp_w[i] = w[i];
}
AddRoundKey(state, temp_w); // AddRoundKey(state, w[0, Nb - 1])
// For round = 1 to 1 to round = 9
for (int i = 1; i < 10; i++)
{
SubBytes(state);
ShiftRows(state);
MixColumns(state);
for (int j = 0; j < 16; j++) {
temp_w[j] = w[16 * i + j];
}
AddRoundKey(state, temp_w); // AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
}
// Last round. Round =10
SubBytes(state);
ShiftRows(state);
for (int i = 0; i < 16; i++) {
temp_w[i] = w[160 + i];
}
AddRoundKey(state, temp_w); // AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
for (int i = 0; i < 16; i++)
out[i] = state[i];
}
// InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
void InvCipher(unsigned char in[16], unsigned char out[16], unsigned char w[176]) {
unsigned char state[16];
unsigned char temp_w[16];
//state = in
for (int i = 0; i < 16; i++) {
state[i] = in[i];
}
for (int i = 0; i < 16; i++) {
temp_w[i] = w[160 + i];
}
AddRoundKey(state, temp_w); // AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
for (int i = 9; i >= 1; i--) {
InvShiftRows(state);
InvSubBytes(state);
for (int j = 0; j < 16; j++) {
temp_w[j] = w[16 * i + j];
}
AddRoundKey(state, temp_w);
InvMixColumns(state); // AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]);
}
// Last round
InvShiftRows(state);
InvSubBytes(state);
for (int i = 0; i < 16; i++) {
temp_w[i] = w[i];
}
AddRoundKey(state, temp_w); // AddRoundKey(state, w[0, Nb-1])
for (int i = 0; i < 16; i++) {
out[i] = state[i];
}
}