I am having a problem with a vigenere decryption method I am writing.
I have tried to solve this but really can't figure out why this is happening.
I get a java.lang.StringIndexOutOfBoundsException and while I know what this means, I don't know why it occurs in this instance.
The method takes a ciphertext and key string as an argument, and first loops through all letters in the key and converts them to the number they are in the alphabet (e.g. a=0,b=1,etc..). Then it loops though all the letters in the ciphertext and shifts them by the amount given in the key.
Expand|Select|Wrap|Line Numbers
- public String VigenereDecrypt(String Ciphertext, String Key){
- int KeyLength = Key.length();
- int[] ShiftAmounts = new int[KeyLength];
- String Plaintext = "";
- for(int a=0;a<KeyLength;a++){
- ShiftAmounts[a] = Alphabet.indexOf(Key.substring(a,1));
- }
- for(int i=0;i<Ciphertext.length();i++){
- int ShiftAmount = i % KeyLength;
- String Sub = Ciphertext.substring(i,1);
- String ShiftedSub = Shift(Sub,ShiftAmount);
- Plaintext += ShiftedSub;
- }
- return Plaintext;
- }
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
and it occurs at line six of the block of code shown here.