我遇到的问题是只有解密才能给我正确的结果。代码在加密方面运行良好,但在解密时会返回错误的结果。 我不知道是什么问题,只有解密它不起作用。有人可以帮助我吗?
//main
public static void main(String[] args) {
int key[]=new int[26];
int ikey[]=new int[26];
String EncMsg =JOptionPane.showInputDialog(null, "enter plain text ");
String plaintext = (EncMsg).replaceAll("\\s","").toLowerCase();
for(int h=0;h<key.length;h++){
String MsgKey=JOptionPane.showInputDialog(null,"enter random keys");
key[h]= Integer.parseInt(MsgKey);
}
//total means collect all letters in one sentence
String total="";
for (int i = 0; i < plaintext.length(); i++) {
char ch = plaintext.charAt(i);
int letterNumber = convertLetter2Number(ch);
int enc = key[letterNumber];
total += convertNumber2Letter(enc);
}
// generating inverted key array
for (int i=0; i<26; i++)
{
for (int j =0; j<26; j++)
{
if(j== key[i])
{
ikey[j] = i ;
break;
}}
}
String total2="";
for (int i = 0; i < total.length(); i++) {
char result = total.charAt(i);
int letterNumber = convertLetter2Number(result);
int dec= ikey[letterNumber];
total2 += convertNumber2Letter(dec);
}
JOptionPane.showMessageDialog(null,"Encryption message : "+total);
JOptionPane.showMessageDialog(null,"Decryption message : "+total2);
}
//convert number to letters ( it has to be random )
public static char convertNumber2Letter(int key){
char[] letters = new char[26];
letters[0]='b';
letters[1]='a';
letters[2]='d';
letters[3]='c';
letters[4]='f';
letters[5]='e';
letters[6]='h';
letters[7]='g';
letters[8]='j';
letters[9]='i';
letters[10]='l';
letters[11]='k';
letters[12]='n';
letters[13]='m';
letters[14]='p';
letters[15]='o';
letters[16]='r';
letters[17]='q';
letters[18]='t';
letters[19]='s';
letters[20]='v';
letters[21]='u';
letters[22]='x';
letters[23]='w';
letters[24]='z';
letters[25]='y';
return letters[key];
}
// convert letter to number ( arranged )
public static int convertLetter2Number(char ltr){
if(ltr=='a'){
return 0;
}else if(ltr=='b'){
return 1;
}else if(ltr=='c'){
return 2;
}else if(ltr=='d'){
return 3;
}else if(ltr=='e'){
return 4;
}else if(ltr=='f'){
return 5;
}else if(ltr=='g'){
return 6;
}else if(ltr=='h'){
return 7;
}else if(ltr=='i'){
return 8;
}else if(ltr=='j'){
return 9;
}else if(ltr=='k'){
return 10;
}else if(ltr=='l'){
return 11;
}else if(ltr=='m'){
return 12;
}else if(ltr=='n'){
return 13;
}else if(ltr=='o'){
return 14;
}else if(ltr=='p'){
return 15;
}else if(ltr=='q'){
return 16;
}else if(ltr=='r'){
return 17;
}else if(ltr=='s'){
return 18;
}else if(ltr=='t'){
return 19;
}else if(ltr=='u'){
return 20;
}else if(ltr=='v'){
return 21;
}else if(ltr=='w'){
return 22;
}else if(ltr=='x'){
return 23;
}else if(ltr=='y'){
return 24;
}else if(ltr=='z'){
return 25;
}
else {
return -1;
}
}}
//end