Java: esempio gestione di un vettore usato per il cifrario di Cesare

Vincent Van Gogh

Questo programma elaborato dallo studente Daniel Amadori che segue il corso di informatica e telecomunicazioni presso IISS Galileo Galilei di Bolzano, evidenzia come si può usare la definizione tradizionale di un vettore ed applicarlo al cifrario di Cesare:

import java.io.*;

class Vigenere{
char cifrario[];

int position(char x){
int i= 0;
while( i < 26){
if(x == cifrario[i])
break;
i++;
}
return i;
}

char shifter(char x,int p){
p += position(x);
if(p < 26)
return cifrario[p];
else
return cifrario[p-26];
}

String cifratore(String x, String password){
String tmp =””;
for(int i= 0,j= 0; i < x.length(); i++,j++){
if(j >= password.length())
j= 0;
tmp += shifter(x.charAt(i), position( password.charAt(j) ) );
}
return tmp;
}
String decifratore(String x, String password){
String tmp =””;
for(int i= 0,j= 0; i < x.length(); i++,j++){
if(j >= password.length())
j= 0;
tmp += shifter(x.charAt(i), 26-position( password.charAt(j) ) );
}
return tmp;
}
Vigenere(){
cifrario = new char[26];
cifrario[0] = ‘a’;
for(int i = 1; i < 26; i++){
cifrario[i] += cifrario[i-1]+1;
}
}

}

public class crittazione {

public static void main (String args[]) {
BufferedReader input = new BufferedReader(new InputStreamReader( System.in ) );
Vigenère a = new Vigenère();

String data =””, key =””, output =””;

System.out.print(“Scegliere se cifrare o decifrare\n 1. Cifrare\n 2.Decifrare\n Cosa scegli: “);
int chose =0;
try {
chose = Integer.parseInt(input.readLine());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“Inserire il testo:”);
try {
data = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“Inserire la chiave:”);
try {
key = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}

if( chose == 1)
output = a.cifratore(data, key);
else if( chose == 2)
output = a.decifratore(data, key);
else
System.out.println(“Scelta non valida”);

System.out.println(output);
}
}

 

Questa voce è stata pubblicata in Senza categoria. Contrassegna il permalink.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *