Java Caesar Cipher,使用2个密钥

时间:2015-12-26 14:26:04

标签: java encryption

使用两个Caesar Cipher密钥描述的算法加密以下短语,key1 = 8,key2 = 21.

中午在会议室里戴着帽子参加一个惊喜派对。 YELL LOUD!

什么是加密字符串?

(注意:您的加密字符串应保留间距和标点符号。)

原始输入是

中午在会议室里戴着帽子参加一个惊喜派对。 YELL LOUD!

期望的结果是

io iwjv jz dv bcm kjvammmikz mwju edbc twpz pvb wi awm v ncmxmqnm xvzog。 tmgt tjcy!

我无法为此问题编写正确的Java代码。请帮助,非常感谢!

我的代码是

import edu.duke.*;

public class CaesarCipher {
    public String encrypt(String input, int key1, int key2) {
        //Make a StringBuilder with message (encrypted)
        StringBuilder encrypted = new StringBuilder(input);
        //Write down the alphabet
        String checker = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String alphabet = checker.toLowerCase();
        //Compute the shifted alphabet
        String shiftedAlphabet1 = alphabet.substring(key1)+
        alphabet.substring(0,key1);
        String shiftedAlphabet2 = alphabet.substring(key2) + alphabet.substring(0,key2);
        //Count from 0 to < length of encrypted, (call it i)
        for(int i = 0; i < encrypted.length(); i+=2) {
            //Look at the ith character of encrypted (call it currChar)
            char currChar1 = encrypted.charAt(i);
            int j = i+1;
            char currChar2 = encrypted.charAt(j);
            //Find the index of currChar in the alphabet (call it idx)
            int idx1 = alphabet.indexOf(currChar1);
            int idx2 = alphabet.indexOf(currChar2);
            //If currChar is in the alphabet
            if(idx1 != -1){
                //Get the idxth character of shiftedAlphabet (newChar)
                char newChar1 = shiftedAlphabet1.charAt(idx1);
                encrypted.setCharAt(i, newChar1);

                char newChar2 = shiftedAlphabet2.charAt(idx2);
                encrypted.setCharAt(j, newChar2);
                }
                //Replace the ith character of encrypted with newChar

            }
            //Otherwise: do nothing
        }
        //Your answer is the String inside of encrypted
        return encrypted.toString();
    }
    public void testCaesar() {
        int key1 = 8;
        int key2 = 21;
        FileResource fr = new FileResource();
        String messagechecker = 'At noon be in the conference room with your hat on for a surprise party. YELL LOUD!';
        String message = messagechecker.toLowerCase();
        String encrypted = encrypt(message, key1, key2);
        System.out.println(encrypted);
        String decrypted = encrypt(encrypted, 26-key1,26-key2);
        System.out.println(decrypted);
    }
}

4 个答案:

答案 0 :(得分:0)

要求:“(注意:您的加密字符串应保留间距和标点符号。)”不由代码处理,特别是字母表仅包含小写字母。您将需要处理从0x20到0x7f的所有字符代码。

对于“double”Caesar Cipher创建一个子程序,在字符串上执行单个Caesar Cipher,然后首先使用原始输入和第一个键调用该函数,然后再使用该输出和第二个键调用该函数。

答案 1 :(得分:0)

我看到当idx2大于for循环的索引时出现问题(即j + 1&gt; encrypted.length())。要计算idx2,你需要检查i + 1(j)的大小。

if (i+1 < encrypted.length()) {
     int j = i+1;
     char ch2 = encrypted.charAt(j);
     char currChar2 = Character.toLowerCase(ch2);
     //Find the index of currChar in the alphabet (call it idx)
     int idx2 = alphabet.indexOf(currChar2);
        if (idx2 != -1) {
           char newChar2 = shiftedAlphabet2.charAt(idx2);
           //Replace the ith character of encrypted with newChar
           encrypted.setCharAt(j, newChar2);
        }
     }
}

答案 2 :(得分:0)

//这是完整的正确答案

public class CaesarCipher {
//this method to encrypt a messgae using a key 
String encrypt (String input, int key){

// convert the original message to temp upper case letters  
String input2 = input.toUpperCase(); 
// using string builder rather than normal string
StringBuilder sb= new StringBuilder(input2);
// default alphabet
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// shiftted alphabet
String shifttedAlphabet= alphabet.substring(key)+alphabet.substring(0,key);

// itterating around the original message to get each char and then getting its index
// then getting the equilvent char in the shiftted alphabet
for (int i = 0; i <sb.length();i++){

char currentChar = sb.charAt(i);
int currentIndex = alphabet.indexOf(currentChar);

if (currentIndex != -1){
char shifttedChar = shifttedAlphabet.charAt(currentIndex);
sb.setCharAt(i,shifttedChar);
                       }
}
// converting the builder string to a normal string 
String encrypted = sb.toString();
// getting every char to its normal case even lower or upper
for (int i =0 ;i < input.length(); i ++){
boolean upper = Character.isUpperCase(input.charAt(i));
if(upper){sb.setCharAt(i,Character.toUpperCase(encrypted.charAt(i)));}
else {sb.setCharAt(i,Character.toLowerCase(encrypted.charAt(i)));}

}
// restting the encrypted message after editting to the lower nad upper case state
encrypted = sb.toString();
// returning the encrypted string 
return encrypted;
}

// this method to encrypt using two keys
String encryptTwoKeys (String input ,int key1 , int key2){
   String encryptedKey1= encrypt (input, key1); 
   String encryptedKey2= encrypt (input, key2); 

   StringBuilder finalEncrypted = new StringBuilder (input);



    for (int i = 0 ; i <encryptedKey1.length();i +=2){
    char currentChar = encryptedKey1.charAt(i);
     finalEncrypted.replace(i, i+1,String.valueOf(currentChar));


    }

    for (int i = 1 ; i <encryptedKey2.length();i +=2){
    char currentChar = encryptedKey2.charAt(i);
     finalEncrypted.replace(i, i+1,String.valueOf(currentChar));


    }

return finalEncrypted.toString();
}

void testEncryptTwoKeys(){
String encrypted = encryptTwoKeys("At noon be in the conference room with your hat on for a surprise party. YELL LOUD!", 8, 21);
System.out.println (encrypted);
String decrypted = encryptTwoKeys(encrypted, 26-8, 26-21);
System.out.println (decrypted);


}

void testEncrypt(){
FileResource fr = new FileResource();
String message = fr.asString();
String encrypted = encrypt(message, 15);
System.out.println("key is " +15+ "\n" + encrypted);

}

}

答案 3 :(得分:0)

import edu.duke.*;

public class CaesarCipher {
//this method to encrypt a messgae using a key 
String encrypt (String input, int key){
// convert the original message to temp upper case letters  
String input2 = input.toUpperCase(); 
// using string builder rather than normal string
StringBuilder sb= new StringBuilder(input2);
// default alphabet
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// shiftted alphabet
String shifttedAlphabet= alphabet.substring(key)+alphabet.substring(0,key);

// itterating around the original message to get each char and then getting its index
// then getting the equilvent char in the shiftted alphabet
for (int i = 0; i <sb.length();i++){

char currentChar = sb.charAt(i);
int currentIndex = alphabet.indexOf(currentChar);

if (currentIndex != -1){
char shifttedChar = shifttedAlphabet.charAt(currentIndex);
sb.setCharAt(i,shifttedChar);
                       }
}
// converting the builder string to a normal string 
String encrypted = sb.toString();
// getting every char to its normal case even lower or upper
for (int i =0 ;i < input.length(); i ++){
boolean upper = Character.isUpperCase(input.charAt(i));
if(upper){sb.setCharAt(i,Character.toUpperCase(encrypted.charAt(i)));}
else {sb.setCharAt(i,Character.toLowerCase(encrypted.charAt(i)));}

}
// restting the encrypted message after editting to the lower nad upper case state
encrypted = sb.toString();
// returning the encrypted string 
return encrypted;
}`enter code here`

// this method to encrypt using two keys
String encryptTwoKeys (String input ,int key1 , int key2){
   String encryptedKey1= encrypt (input, key1); 
   String encryptedKey2= encrypt (input, key2); 

   StringBuilder finalEncrypted = new StringBuilder (input);



    for (int i = 0 ; i <encryptedKey1.length();i +=2){
    char currentChar = encryptedKey1.charAt(i);
     finalEncrypted.replace(i, i+1,String.valueOf(currentChar));


    }

    for (int i = 1 ; i <encryptedKey2.length();i +=2){
    char currentChar = encryptedKey2.charAt(i);
     finalEncrypted.replace(i, i+1,String.valueOf(currentChar));


    }

return finalEncrypted.toString();
}

void testEncryptTwoKeys(){
String encrypted = encryptTwoKeys("Can you imagine life WITHOUT the internet AND computers in your pocket?", 21,8 );
System.out.println (encrypted);
String decrypted = encryptTwoKeys(encrypted, 26-21, 26-8);
System.out.println (decrypted);


}

   void testEncrypt()
   {
   FileResource fr = new FileResource();
   String message = fr.asString();
   String encrypted = encrypt(message, 15);
   System.out.println("key is " +15+ "\n" + encrypted);

  }
}