I have written a java program that encodes with the Vigenere cipher the encryption works fine, however the decryption does not for some special cases.
For example if the plain text is 'k' and the key is 'y' it correctly produces the cipher text 'i' ((10 + 24 = 34 % 26 = 8))
however when decrypting the cipher text is 'i' and the key is 'y' I get((8-24) =-16%26 = -16)) which even if it was positive would be Q. When it should correctly decrypt back to 'k' which would be 10.
Can anyone help me out here? I can post more code if needed.
---Link to wiki Viginare cipher algorithm http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher ---
//decryption
else{
for (int i=0; i < a.length(); i++){
for (int j=0; j < full.length(); j++){
//finding the index of the current cipher text letter
if (a.charAt(i) == full.charAt(j)){
positionP = j;
}
//finding the index of the current key letter
if(key.charAt(i)==full.charAt(j)){
positionK = j;
}
}
//using the formula for vigenere encoding it adds the newly encrypted character to the output
output = output + full.charAt((positionP - positionK)%26);
}
}
Note that the remainder operator in Java is defined such that the magnitude of the result is always less than the magnitude of the divisor, and the result of the remainder operation is negative if the dividend is negative [JLS].
You may obtain the desired output by doing:
output = output + full.charAt((positionP - positionK + 26)%26);
If positionP-positionK
is positive, the addition doesn't change the result (because 26%26=0). If positionP-positionK
is negative (between -25 and 0), then positionP - positionK + 26
will be non-negative, yielding the correct result.