Ciao a tutti, sto scrivendo per un esame un programma che sfrutta l'algoritmo di vigenere solo che non riesco a farlo funzionare, ho letto diverse spiegazioni ma quando cambio il minChar o il maxChar non funziona oppure anche solo con alcune combinazioni di chiavi e testo.
Penso che il problema sia nel fatto che la formula calcola fuori dai limiti di minChar e maxChar.
codice:
class Vigenere {
private final int minChar;
private final int maxChar;
private final String encryptKey;
public static void main(String argv[]) {
String key = "VERME";
String in = "RAPPORTOIMMEDIATO";
Vigenere v = new Vigenere(65, 90, key);
System.out.println("Plain:\t\t" + in);
System.out.println("Key:\t\t" + key);
String cryptedPhrase = v.encryptString(in);
System.out.println("Crypted:\t" + cryptedPhrase);
System.out.println("Decrypted:\t" + v.decryptString(cryptedPhrase));
}
public String encryptString(String phrase) {
String result = "";
int keyIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
char currentChar = phrase.charAt(i);
char resultChar;
if (minChar <= currentChar && currentChar <= maxChar) {
char keyChar = encryptKey.charAt(keyIndex);
int rangeLength = maxChar - minChar;
resultChar = (char) (((int) currentChar + (int) keyChar - 2 * minChar) % rangeLength + minChar);
result += resultChar;
} else {
result += currentChar;
}
keyIndex = (keyIndex + 1) % encryptKey.length();
}
return result;
}
public String decryptString(String cryptedPhrase) {
String result = "";
int keyIndex = 0;
for (int i = 0; i < cryptedPhrase.length(); i++) {
char currentChar = cryptedPhrase.charAt(i);
char resultChar;
if (minChar <= currentChar && currentChar <= maxChar) {
char keyChar = encryptKey.charAt(keyIndex);
//MinChar e MaxChar sono compresi
int rangeLength = maxChar - minChar;
resultChar = (char) (((int) currentChar - (int) keyChar) % rangeLength + minChar);
if (resultChar < minChar) {
resultChar += rangeLength;
}
result += resultChar;
} else {
result += currentChar;
}
keyIndex = (keyIndex + 1) % encryptKey.length();
}
return result;
}
public Vigenere(int minChar, int maxChar, String encryptKey) {
for (int i = minChar; i <= maxChar; i++) {
System.out.print((char) i + "");
}
System.out.println("");
this.minChar = minChar;
this.maxChar = maxChar;
this.encryptKey = encryptKey;
}
}