gpt4 book ai didi

java - 如何使解密方法起作用以将加密的字符串返回到原始字符串?

转载 作者:行者123 更新时间:2023-12-01 04:17:58 26 4
gpt4 key购买 nike

我被指示编写一个程序,该程序应该通过用户输入来加密给定的字符串,并为输入的每个字母生成一个随机加密字符,同时确保替换原始字符中多次出现的相同字符由编码字符串中的相同字符组成。

我还必须确保原始字符中没有两个字符在编码字符串中被编码为相同字符,以便能够成功解密。

但是,解密后返回的字符串与最初的字符串完全不同。任何帮助或建议将不胜感激。

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();

}
}

最佳答案

您正在解密用户输入的字符串,为了解密消息,您必须传递您获得的加密字符串的参数。

String SecretDecrypt = cipher.decrypt(secretEncrypt);

关于java - 如何使解密方法起作用以将加密的字符串返回到原始字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com