Java凯撒密码,使用2个密钥

cwtwac6a  于 2023-02-07  发布在  Java
关注(0)|答案(5)|浏览(137)

使用针对使用两个Caesar Cipher密钥(key1 = 8,key2 = 21)所描述的算法对以下短语进行加密。
中午的时候,戴上你的帽子,在会议室里参加一个惊喜派对。大声喊出来!
什么是加密字符串?
(Note:加密字符串应保留空格和标点符号。)
原始输入为
中午的时候,戴上你的帽子,在会议室里参加一个惊喜派对。大声喊出来!
所需结果为
我是一个jv的dv bcm的kjvammmikz的mwju edbc两个pvb与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);
    }
}
aiazj4mn

aiazj4mn1#

要求:“(注意:您的加密字符串应保留空格和标点符号。)”不受代码处理,特别是字母表只包含小写字母。您将需要处理从0x20到0x7f的所有字符代码。
对于“double”凯撒密码,创建一个子例程,对字符串执行一个凯撒密码,然后首先用原始输入和第一个密钥调用该函数,然后再用输出和第二个密钥调用该函数。

wgx48brx

wgx48brx2#

我发现当idx2大于for循环的索引时(即j+1〉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);
        }
     }
}
guykilcj

guykilcj3#

//以下是完整的正确答案

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

}

}

thigvfpy

thigvfpy4#

对于导入各自的库,完整答案如下:

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

  }
}
t1qtbnec

t1qtbnec5#

import java.util.Scanner;

public class caesarCipher {
 
   /* This method is used to both encrypt and decrypt */

public static String encrypt(String input, int key1, int key2) {
    int pos = -1, pos1 = -1;
   
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /* Take whole 
    alphabet as a string */
    
  /* modify the encrypted string use string builder */
   
   StringBuilder encrypted = new StringBuilder(input);
  
         for (int i = 0; i < encrypted.length(); i++) {
             /* take each character from the string */
        char sample = encrypted.charAt(i);
        /* We have to perform only with alphabet */
        if (Character.isAlphabetic(sample)) {
            /* check the position as key1 for even and key2 for odd position */
            if (i % 2 == 0) {
                /*
                 * if the character is uppercase nothing to do
                 * cause we take alphabet in total uppercase
                 */
                if (Character.isUpperCase(sample)) {
                    /* find the position of the character from the alphabet */
                    pos = alphabet.indexOf(sample);
                    /* set the position as key */
                    pos = (pos + key1) % 26;
                    /* find the letter with updated position from the alphabet */
                    char res = alphabet.charAt(pos);
                    /* modify it */
                    encrypted.setCharAt(i, res);

                }
                /* if the character is in lowercase */
                else {
                    /* convert it to uppercase to find */
                    pos = alphabet.indexOf(Character.toUpperCase(sample));
                    pos = (pos + key1) % 26;
                    char res = alphabet.charAt(pos);
                    /* convert the desired output in lowercase then modify it */
                    encrypted.setCharAt(i, Character.toLowerCase(res));

                }
                pos = -1;
            }
            /* same above procedure in case of odd position */
            else {
                if (Character.isUpperCase(sample)) {
                    pos1 = alphabet.indexOf(sample);
                    pos1 = (pos1 + key2) % 26;
                    char res1 = alphabet.charAt(pos1);
                    encrypted.setCharAt(i, res1);

                } else {
                    pos1 = alphabet.indexOf(Character.toUpperCase(sample));
                    pos1 = (pos1 + key2) % 26;
                    char res1 = alphabet.charAt(pos1);
                    encrypted.setCharAt(i, Character.toLowerCase(res1));

                }
                pos1 = -1;
            }
        }
    }
    return encrypted.toString();

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the string:");
    String input = sc.nextLine();
    System.out.println("Enter the key1:");
    int key1 = sc.nextInt();
    System.out.println("Enter the key2:");
    int key2 = sc.nextInt();
    /*
     * for both encryt and decrypt use the same method but for decrypt key will be
     * 26-key
     */
    String e = encrypt(input, key1, key2);
    System.out.println("...........After encryption...........\n" + e);
    String d = encrypt(e, (26 - key1), (26 - key2));
    System.out.println("...........After decryption...........\n" + d);
} 
        }
/* Compile and enjoy */

相关问题