Java Program on Multiplicative Cipher

Java Program on Multiplicative Cipher

This Java program is to demonstrate Multiplicative Cipher.

Algorithm

The Multiplicative Cipher can be expressed in a more mathematical form as follows:

En(x) = (x*n) mod 26

In plain terms, this means that the encryption of a letter x is equal to a shift of x *n, where n is the number of letters shifted. The result of the process is then taken under modulo division, essentially meaning that if a letter is shifted past the end of the alphabet, it wraps around to the beginning i.e we again start from a.

Decryption of the encrypted text (ciphertext) is the opposite, we multiple the encrypted text with the multiplicative inverse of n to get back the original text.

Dn(x) = (x*p) mod 26  where p=multiplicative inverse of n.

If you need a dry run of the program or any other query, then kindly leave a comment in the comment box or mail me, I would be more than happy to help you.

Program

import java.util.*;

class multiplicativeCipher
{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int shift,i,n;
		String str;
		String str1="";
		String str2="";
		System.out.println("Enter the plaintext");
		str=sc.nextLine();
		str=str.toLowerCase();
		n=str.length();
		char ch1[]=str.toCharArray();
		char ch3;
		char ch4;
		System.out.println("Enter the value by which each letter of the string is to be shifted");
		shift=sc.nextInt();
		
		System.out.println();		
		System.out.println("Encrypted text is");
		
		for(i=0;i<n;i++)
		{
			if(Character.isLetter(ch1[i]))
			{
				ch3=(char)(((int)ch1[i]*shift-97)%26+97);
				str1=str1+ch3;
			}
			else if(ch1[i]==' ')
			{
				str1=str1+ch1[i];
			}				
		}
		System.out.println(str1);

		//Caclulation of multiplicative inverse
		int q=0,flag=0;
		for(i=0;i<26;i++)
    		{
        		if(((i*26)+1)%shift==0)
        		{
            			q=((i*26)+1)/shift;
            			break;
        		}
    		}


		System.out.println();
		System.out.println("Decrypted text is");
		char ch2[]=str1.toCharArray();
		for(i=0;i<str1.length();i++)
		{
			if(Character.isLetter(ch2[i]))
			{
				
				ch4=(char)(((int)ch2[i]*q-97)%26+97);
				str2=str2+ch4;
			}
			
			else if(ch2[i]==' ')
			{
				str2=str2+ch2[i];
			}					
		}
		System.out.println(str2);
	}
}

Output

 

Share Me!