使用针对使用两个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);
}
}
5条答案
按热度按时间aiazj4mn1#
要求:“(注意:您的加密字符串应保留空格和标点符号。)”不受代码处理,特别是字母表只包含小写字母。您将需要处理从0x20到0x7f的所有字符代码。
对于“double”凯撒密码,创建一个子例程,对字符串执行一个凯撒密码,然后首先用原始输入和第一个密钥调用该函数,然后再用输出和第二个密钥调用该函数。
wgx48brx2#
我发现当idx2大于for循环的索引时(即j+1〉encrypted.length()),问题出现了。为了计算idx2,需要检查i+1(j)的大小。
guykilcj3#
//以下是完整的正确答案
}
thigvfpy4#
对于导入各自的库,完整答案如下:
t1qtbnec5#