替换密码加密器代码给出但没有解密器

时间:2015-05-06 04:40:26

标签: java encryption

所以给出了加密代码

// encrypt looks up the character at the appropriate place
// in the encryption String and substitutes it.
public void encrypt (StringBuilder text)
{  
   for (int i=0; i<text.length(); i++)
   {
       char ch = text.charAt(i);
       if ('A' <= ch && ch <= 'Z')
       {
           int index = ALPHABET.indexOf(ch);
           text.setCharAt(i, encryptionString.charAt(index));
       }
   }
}

我如何修改上面的代码才能解密?

public class SubstitutionCipher
{
// The alphabet as a String.  We use this for both
// encoding and decoding
public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// The encryption string is how we represent the table
// of values.  The first character in the String 
// is substituted for 'A', the second for 'B', etc.
private String encryptionString;

/**
 * Constructor for objects of class Substitution
 */
public SubstitutionCipher(String substitutionString)
{
    if (substitutionString.length() != 26)
    {
        System.out.println ("Illegal substitution string " 
                            + substitutionString);
        encryptionString = ALPHABET;
    }
    else
    {
        encryptionString = substitutionString;
    }
}

// encrypt looks up the character at the appropriate place
// in the encryption String and substitutes it.
public void encrypt (StringBuilder text)
{  
   for (int i=0; i<text.length(); i++)
   {
       char ch = text.charAt(i);
       if ('A' <= ch && ch <= 'Z')
       {
           int index = ALPHABET.indexOf(ch);
           text.setCharAt(i, encryptionString.charAt(index));
       }
   }
}

// decrypt looks up the character at the appropriate place
// in the alphabet and substitutes it.
public void decrypt (StringBuilder text)
{


   for (int i=0; i<text.length(); i++)
   {
       char ch = text.charAt(i);
       if ('A' <= ch && ch <= 'Z')
       {
           int index = ALPHABET.indexOf(ch);
           text.setCharAt(i, encryptionString.charAt(index));
       }
   }
}    

}

1 个答案:

答案 0 :(得分:1)

在解密时你只需要反向加密,但在你的代码中,你正在做同样的事情,所以改成它:

public void decrypt (StringBuilder text)
{    
   for (int i=0; i<text.length(); i++)
   {
       char ch = text.charAt(i);
       if ('A' <= ch && ch <= 'Z')
       {
           int index =encryptionString.indexOf(ch);
           text.setCharAt(i, ALPHABET.charAt(index));
       }
   }
}