我被指示编写一个程序,该程序应通过用户的输入加密给定的字符串,并为每个输入的字母生成一个随机加密字符,同时确保在原始字符中多次出现的相同字符被相同的字符替换编码字符串中的字符。
我还必须确保原始字符中没有两个字符被编码为编码字符串中的相同字符,以便能够成功解密。
然而,解密给了我一个与我最初拥有的完全不同的字符串。任何帮助或建议将不胜感激。
public class Caesar {
public static final int ALPHASIZE = 26; // upper case alphabets
public static final char[] alpha = {'A','B','C','D',
'E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z'};
protected char[] encrypt = new char [ALPHASIZE]; // encryption array
protected char[] decrypt = new char [ALPHASIZE]; // decryption array
// constructor that initializes the encryption and decryption arrays
Random randomGen = new Random();
public Caesar() {
int random = randomGen.nextInt(ALPHASIZE);
{
for(int i=0; i< ALPHASIZE; i++)
encrypt[i]=alpha[(i+random)%ALPHASIZE];
for(int i=0; i< ALPHASIZE; i++)
decrypt[encrypt[i]- 'A']=alpha[i];
}
}
// encryption method
public String encrypt(String secret)
{
char[] mess = secret.toCharArray(); // the message array
for(int i=0; i<mess.length; i++) // encryption loop
if(Character.isUpperCase(mess[i])) // a letter to change
mess[i]=encrypt [mess[i]-'A']; // use letter as index
else if(Character.isLowerCase(mess[i])) // a letter to change
mess[i]=(new String(""+encrypt [mess[i]-'a'])).toLowerCase().charAt(0); // use letter as index
return new String (mess);
}
// decryption method
public String decrypt (String secret)
{
char[] mess = secret.toCharArray();
for(int i=0; i<mess.length; i++)
if (Character.isUpperCase(mess[i]))
mess[i]=decrypt[mess[i]-'A'];
else if(Character.isLowerCase(mess[i])) // a letter to change
mess[i]=(new String(""+decrypt [mess[i]-'a'])).toLowerCase().charAt(0); // use letter as index
return new String (mess);
}
}
Test Class
public class CaesarTryOut {
public static void main(String[] args) {
System.out.println("Please enter your message:");
Scanner scan = new Scanner(System.in);
String c = scan.nextLine();
System.out.println();
System.out.println("You entered the following message:");
System.out.println(c);
System.out.println();
Caesar cipher = new Caesar();
String code = c;
String secretEncrypt = cipher.encrypt(c);
System.out.println("Your string has been encrypted to:");
System.out.println(secretEncrypt);
System.out.println();
String secretDecrypt = cipher.decrypt(c);
System.out.println("Your message has been decrypted to:");
System.out.println(secretDecrypt);
System.out.println();
}
}