This is a java program to implement Affine Cipher. The affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. As such, it has the weaknesses of all substitution ciphers. Each letter is enciphered with the function (ax+b)mod(26), where b is the magnitude of the shift.
Here is the source code of the Java Program to Implement Affine Cipher. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
package com.sanfoundry.setandstring;
import java.util.Scanner;
public class AffineCipher
{
public static String encryptionMessage(String Msg)
{
String CTxt = "";
int a = 3;
int b = 6;
for (int i = 0; i < Msg.length(); i++)
{
CTxt = CTxt + (char) ((((a * Msg.charAt(i)) + b) % 26) + 65);
}
return CTxt;
}
public static String decryptionMessage(String CTxt)
{
String Msg = "";
int a = 3;
int b = 6;
int a_inv = 0;
int flag = 0;
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
if (flag == 1)
{
a_inv = i;
System.out.println(i);
}
}
for (int i = 0; i < CTxt.length(); i++)
{
Msg = Msg + (char) (((a_inv * ((CTxt.charAt(i) - b)) % 26)) + 65);
}
return Msg;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the message: ");
String message = sc.next();
System.out.println("Message is :" + message);
System.out.println("Encrypted Message is : "
+ encryptionMessage(message));
System.out.println("Decrypted Message is: "
+ decryptionMessage(encryptionMessage(message)));
sc.close();
}
}
Output:
$ javac AffineCipher.java $ java AffineCipher Enter the message: SANFOUNDRY Message is :SANFOUNDRY Encrypted Message is : VTGIJBGCSN 9 Decrypted Message is: SANFOUNDRY
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Check Java Books
- Practice Programming MCQs
- Practice Information Technology MCQs
- Apply for Java Internship
- Apply for Computer Science Internship