Vigenère Cipher. In the Vigenère Cipher, we use a special keyword to encrypt a message. We represent each letter of the alphabet as a number from 0-25. In order, we add each letter from the keyword to the message and mod by 26. If the keyword is shorter than the message, we simply repeat the keyword. For example, lets say that the message is HOWSTUFFWORKS and the keyword is CIPHER. The following table shows how we can find the final version of the ciphertext, borrowed from How Stuff Works. Plain Text: HOWSTUFFWORKS Keyword: CIPHER Cipher Text: JWLZXLHNLVVBU Your mission is to write a program that will read a message and a keyword and apply the Vigenère Cipher to it.
Your main() method should prompt the user for some plain text. Then, it should prompt the user for a keyword. You may assume that both the plain text and the keyword contain no spaces and are only made up of upper case letters. To perform the encryption, you need to loop through the plain text and add each letter from the keyword to it, mod 26. Unfortunately, neither the letters in the plain text nor in the keyword have values between 0 and 25. You will have to convert those letter values so that they are between 0 and 25, then do the add, then do the mod, then convert them back to the proper ASCII values
Must be in Java.
The following code can be used to implement Vignere Cipher in Java.
// Java code to implement Vigenere Cipher
import java.util.*;
class Vignere
{
// This function generates the key in
// a cyclic manner until it's length isi'nt
// equal to the length of original text
static String generateKey(String str, String key)
{
int x = str.length();
for (int i = 0; ; i++)
{
if (x == i)
i = 0;
if (key.length() == str.length())
break;
key+=(key.charAt(i));
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
static String cipherText(String str, String key)
{
String cipher_text="";
for (int i = 0; i < str.length(); i++)
{
// converting in range 0-25
int x = (str.charAt(i) + key.charAt(i)) %26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text+=(char)(x);
}
return cipher_text;
}
// Driver code
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter the message to be encrypted : ");
String str = sc.nextLine();
System.out.print("Enter the keyword : ");
String keyword = sc.nextLine();
String key = generateKey(str, keyword);
String cipher_text = cipherText(str, key);
System.out.println("Ciphertext : " + cipher_text + "\n");
System.out.println("Original Text : " + str);
}
}
Please upvote the answer if you find it helpful.
Get Answers For Free
Most questions answered within 1 hours.