I'm trying to do a small implementation of a Feistel Cipher. This is what I've been trying:
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;
}
The round function, scramble
is:
private static int scramble(int character, int key, int roundNumber) {
return (int) Math.pow(2 * roundNumber * key, character) % 15;
}
I am attempting to first encrypt the left and right halves of the plaintext, and then run it through the decryption rounds - so by the end, the array's values should be [1,2,3] and [4,5,6] (back to the plaintext). Using a key input of 8, after decryption I'm getting values of [15, 13, 0] and [8, 12, 1]. Where am I going wrong with this?
For simplicity I'm just using a constant as the key right now as well as input of integers as opposed to reading from a file/using byte arrays.
edit:
counting for the loops was incorrect. Changed the "encryption loop" to:
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;
}
The loops now count rounds 1,2,3 (encryption) and 3,2,1 (decryption). However, the decryption still isn't resulting in the correct plaintext.