Java Program to Encode a Message Using Playfair Cipher

This is a java program to implement playfair cipher algorithm. The Playfair cipher or Playfair square is a manual symmetric encryption technique and was the first literal digraph substitution cipher.

Here is the source code of the Java Program to Enode a Message Using Playfair Cipher. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

package com.maixuanviet.setandstring;
 
import java.util.Scanner;
 
public class PlayfairCipherEncryption
{
    private String KeyWord        = new String();
    private String Key            = new String();
    private char   matrix_arr[][] = new char[5][5];
 
    public void setKey(String k)
    {
        String K_adjust = new String();
        boolean flag = false;
        K_adjust = K_adjust + k.charAt(0);
        for (int i = 1; i < k.length(); i++)
        {
            for (int j = 0; j < K_adjust.length(); j++)
            {
                if (k.charAt(i) == K_adjust.charAt(j))
                {
                    flag = true;
                }
            }
            if (flag == false)
                K_adjust = K_adjust + k.charAt(i);
            flag = false;
        }
        KeyWord = K_adjust;
    }
 
    public void KeyGen()
    {
        boolean flag = true;
        char current;
        Key = KeyWord;
        for (int i = 0; i < 26; i++)
        {
            current = (char) (i + 97);
            if (current == 'j')
                continue;
            for (int j = 0; j < KeyWord.length(); j++)
            {
                if (current == KeyWord.charAt(j))
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
                Key = Key + current;
            flag = true;
        }
        System.out.println(Key);
        matrix();
    }
 
    private void matrix()
    {
        int counter = 0;
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                matrix_arr[i][j] = Key.charAt(counter);
                System.out.print(matrix_arr[i][j] + " ");
                counter++;
            }
            System.out.println();
        }
    }
 
    private String format(String old_text)
    {
        int i = 0;
        int len = 0;
        String text = new String();
        len = old_text.length();
        for (int tmp = 0; tmp < len; tmp++)
        {
            if (old_text.charAt(tmp) == 'j')
            {
                text = text + 'i';
            }
            else
                text = text + old_text.charAt(tmp);
        }
        len = text.length();
        for (i = 0; i < len; i = i + 2)
        {
            if (text.charAt(i + 1) == text.charAt(i))
            {
                text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
            }
        }
        return text;
    }
 
    private String[] Divid2Pairs(String new_string)
    {
        String Original = format(new_string);
        int size = Original.length();
        if (size % 2 != 0)
        {
            size++;
            Original = Original + 'x';
        }
        String x[] = new String[size / 2];
        int counter = 0;
        for (int i = 0; i < size / 2; i++)
        {
            x[i] = Original.substring(counter, counter + 2);
            counter = counter + 2;
        }
        return x;
    }
 
    public int[] GetDiminsions(char letter)
    {
        int[] key = new int[2];
        if (letter == 'j')
            letter = 'i';
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                if (matrix_arr[i][j] == letter)
                {
                    key[0] = i;
                    key[1] = j;
                    break;
                }
            }
        }
        return key;
    }
 
    public String encryptMessage(String Source)
    {
        String src_arr[] = Divid2Pairs(Source);
        String Code = new String();
        char one;
        char two;
        int part1[] = new int[2];
        int part2[] = new int[2];
        for (int i = 0; i < src_arr.length; i++)
        {
            one = src_arr[i].charAt(0);
            two = src_arr[i].charAt(1);
            part1 = GetDiminsions(one);
            part2 = GetDiminsions(two);
            if (part1[0] == part2[0])
            {
                if (part1[1] < 4)
                    part1[1]++;
                else
                    part1[1] = 0;
                if (part2[1] < 4)
                    part2[1]++;
                else
                    part2[1] = 0;
            }
            else if (part1[1] == part2[1])
            {
                if (part1[0] < 4)
                    part1[0]++;
                else
                    part1[0] = 0;
                if (part2[0] < 4)
                    part2[0]++;
                else
                    part2[0] = 0;
            }
            else
            {
                int temp = part1[1];
                part1[1] = part2[1];
                part2[1] = temp;
            }
            Code = Code + matrix_arr[part1[0]][part1[1]]
                    + matrix_arr[part2[0]][part2[1]];
        }
        return Code;
    }
 
    public static void main(String[] args)
    {
        PlayfairCipherEncryption x = new PlayfairCipherEncryption();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a keyword:");
        String keyword = sc.next();
        x.setKey(keyword);
        x.KeyGen();
        System.out
                .println("Enter word to encrypt: (Make sure length of message is even)");
        String key_input = sc.next();
        if (key_input.length() % 2 == 0)
        {
            System.out.println("Encryption: " + x.encryptMessage(key_input));
        }
        else
        {
            System.out.println("Message length should be even");
        }
        sc.close();
    }
}

Output:

$ javac PlayfairCipherEncryption.java
$ java PlayfairCipherEncryption
 
Enter a keyword:
Sanfoundry
Sanfoudrybceghiklmpqstvwxz
S a n f o 
u d r y b 
c e g h i 
k l m p q 
s t v w x 
Enter word to encrypt: (Make sure length of message is even)
Learningcenter
Encryption: acndogrmegavgd

Related posts:

Using Spring @ResponseStatus to Set HTTP Status Code
Guide to Spring @Autowired
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Hướng dẫn Java Design Pattern – Template Method
Java Program to Perform Searching Using Self-Organizing Lists
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Using JWT with Spring Security OAuth
Java equals() and hashCode() Contracts
Guide to UUID in Java
Một số nguyên tắc, định luật trong lập trình
New Features in Java 13
Recommended Package Structure of a Spring Boot Project
Spring’s RequestBody and ResponseBody Annotations
Write/Read cookies using HTTP and Read a file from the internet
Java Program to Perform Finite State Automaton based Search
Easy Ways to Write a Java InputStream to an OutputStream
Serve Static Resources with Spring
Java Program to Implement Miller Rabin Primality Test Algorithm
Using a List of Values in a JdbcTemplate IN Clause
Java Program to Check for balanced parenthesis by using Stacks
Cài đặt và sử dụng Swagger UI
Instance Profile Credentials using Spring Cloud
Chuyển đổi từ HashMap sang ArrayList
Guide to the Java ArrayList
Java Program to Find the GCD and LCM of two Numbers
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Tính kế thừa (Inheritance) trong java
Introduction to Spring Security Expressions
Java Program to Implement Pairing Heap
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Java Program to Generate N Number of Passwords of Length M Each