I can't get the decryption part to work (ANY HELP IS APPRECIATED)
I have basically been instructed to write a program which should encrypt a given string by input from the user and generate a random encryption character for each letter that has been input while ensuring that the same character appearing more than once in the original is replaced by the same character in the coded string. I must also ensure that no two characters in the original are coded as the same character in the coded string, in order to enable successful decryption. However the decryption gives me back a completely different string to what I had in the first place, here is my code:
Code:
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]; // rotate alphabet by 3 places
for(int i=0; i< ALPHASIZE; i++)
decrypt[encrypt[i]- 'A']=alpha[i]; // decrypt is reverse of encrypt
}
}
// 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);
}
}
Any help will be greatly appreciated.