Write a program (in any programming language) that would reproduce figure 2.3 on
ID: 3814036 • Letter: W
Question
Write a program (in any programming language) that would reproduce figure 2.3 on page 55 for the Caesar Cipher. Your program should accept as input the ciphertext and produce a tabular listing of all possible plaintexts. Provide the opposite functionality, i.e., given the plaintext, produce all possible ciphertexts for all key values. Test your program against the following two ciphertexts. BZDRZQ'R VHED LTRS AD ZANUD RTROHBHNM KENKMOC PYBDEXK TEFKD (ciphertexts obtained from http://simonsingh.net/cryptography/cryptograms/)
Explanation / Answer
package sample1;
import java.util.Scanner;
public class test
{
public static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainTxt, int shiftKey)
{
plainTxt = plainTxt.toLowerCase();
String cipherTxt = "";
for (int i = 0; i < plainTxt.length(); i++)
{
int charPos = ALPHA.indexOf(plainTxt.charAt(i));
int keyVal = (shiftKey + charPos) % 26;
char replaceVal = ALPHA.charAt(keyVal);
cipherTxt += replaceVal;
}
return cipherTxt;
}
public static String decrypt(String cipherTxt, int shiftKey)
{
cipherTxt = cipherTxt.toLowerCase();
String plainTxt = "";
for (int i = 0; i < cipherTxt.length(); i++)
{
int charPos = ALPHA.indexOf(cipherTxt.charAt(i));
int keyVal = (charPos - shiftKey) % 26;
if (keyVal < 0)
{
keyVal = ALPHA.length() + keyVal;
}
char replaceVal = ALPHA.charAt(keyVal);
plainTxt += replaceVal;
}
return plainTxt;
}
public static void main(String[] args)
{
String message1 ="BZDRZQ’R VHED LTRS AD ZANUD RTROHBHNM";
String message2="KENKMOC PYBDEXK TEFKD";
System.out.println("Possible plain texts for message 1 are :");
for(int i=1;i<=26;i++){
System.out.println("Key "+i+":"+encrypt(message1,i));
System.out.println(" Plaintext :"+decrypt(encrypt(message1,i),i));
}
System.out.println("Possible plain texts for message 2 are :");
for(int i=1;i<=26;i++){
System.out.println("Key "+i+":"+encrypt(message2,i));
System.out.println(" Plaintext :"+decrypt(encrypt(message2,i),i));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.