Caesar cipher is an encryption technique to communicate messages secretly. Each
ID: 3546344 • Letter: C
Question
Caesar cipher is an encryption technique to communicate messages secretly. Each character in the original message is shifted N positions. For example, if N = 1, then the message
I drink only decaf
Becomes
J!esjol!pomz!efdbg
The encrypted message is decrypted to the original message by shifting back every character N positions. Shifting N positions forward and backward is achieved by converting the character to ASCII and adding or subtracting N.
The Caesar cipher is fairly easy to break. But it can be improved by using a repeating key. Instead of shifting each character by a constant amount, we can shift each character by a different amount using a list of key values. If the message is longer than the list of the key value, we just start using the key over again from the beginning. For example, if the key values are
317425
Then the first character is shifted by 3, the second character by 1, and so on. After shifting the sixth character by 5, we start using the key over again. The seventh character is shifted by 3, the eighth by 1, and so on. For example,
Original message:
k
n
o
w
l
e
d
g
e
Key:
3
1
7
4
2
5
3
1
7
Encrypted message:
n
o
v
{
n
j
g
h
j
Write a program that reads in the original text input file and the key value from the user, and uses a user-defined method to encrypt the original text and save the encrypted text into an output file.
Make sure the ASCII value resulting from encryption falls between 32 and 126 (printable characters). For example, if you add 8 (value of N) to 122 (ASCII code for
Original message:
k
n
o
w
l
e
d
g
e
Key:
3
1
7
4
2
5
3
1
7
Encrypted message:
n
o
v
{
n
j
g
h
j
Explanation / Answer
import java.util.Scanner;
class CaesarCipher {
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public String encrypt(String plainText,String shiftKey)
{
plainText = plainText.toLowerCase();
String cipherText="";
for(int i=0;i<plainText.length();i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int l=shiftKey.length();
int m=i%l;
int keyVal = ((int)shiftKey.charAt(m)+charPosition)%26;
char replaceVal = this.ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
class CaesarDemo {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter text");
String plainText = in.nextLine();
System.out.println("Enter the key");
shiftKey = in.nextLine();
CaesarCipher cc = new CaesarCipher();
String cipherText = cc.encrypt(plainText,shiftKey);
System.out.println("Your Plain Text :" + plainText);
System.out.println("Your Cipher Text :" + cipherText);
}
}