我正在尝试做一个Feistel Cipher的小实现。这是我一直在尝试的:
int[] left = {1,2,3};//left half of plaintext
int[] right = {4,5,6};//right half of plaintext
int temp[];//temp for swapping values
//encrypt the plaintext (left and right arrays)
for(int r = 0; r < 3; r++) {//the number of rounds
for(int i = 0; i < right.length; i++){
right[i] = left[i] ^ (scramble(right[i], KEY, r));
}
temp = left;
left = right;
right = temp;
}
//swap left and right array before decryption
temp = left;
left = right;
right = temp;
for(int r = 3; r > 0; r--) {//start from the last round
for(int i = 0; i < right.length; i++) {
right[i] = left[i] ^ (scramble(right[i], KEY, r));
}
//again, swap arrays to do the next round
temp = left;
left = right;
right = temp;
}
圆函数scramble
为:
private static int scramble(int character, int key, int roundNumber) {
return (int) Math.pow(2 * roundNumber * key, character) % 15;
}
我试图首先加密明文的左右两半,然后通过解密轮运行它 - 所以到最后,数组的值应该是 [1,2,3] 和 [4,5,6] (回到明文)。使用 8 的密钥输入,解密后我得到 [15, 13, 0] 和 [8, 12, 1] 的值。我哪里错了?
为简单起见,我现在只是使用常量作为键以及整数的输入,而不是从文件中读取/使用字节数组。
编辑:
循环计数不正确。将“加密循环”更改为:
for(int r = 1; r < 4; r++) {//the number of rounds
for(int i = 0; i < right.length; i++){
right[i] = left[i] ^ (scramble(right[i], KEY, r));
}
temp = left;
left = right;
right = temp;
}
循环现在计算第 1,2,3 轮(加密)和 3,2,1(解密)。但是,解密仍然没有得到正确的明文。