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

时间:2013-10-08 18:22:39

标签: java string encryption

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

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

但是,解密给了我一个完全不同的字符串。任何帮助或建议将不胜感激。

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

}
}

1 个答案:

答案 0 :(得分:0)

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

String secretDecrypt = cipher.decrypt(secretEncrypt);