Java Program to Perform Cryptography Using Transposition Technique

This is a java program to implement transposition technique. In cryptography, a transposition cipher is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes a permutation of the plaintext. That is, the order of the units is changed (the plaintext is reordered). Mathematically a bijective function is used on the characters’ positions to encrypt and an inverse function to decrypt.

Here is the source code of the Java Program to Perform Cryptography Using Transposition Technique. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

package com.maixuanviet.setandstring;
 
public class TranspositionCipher
{
    public static String selectedKey;
    public static char   sortedKey[];
    public static int    sortedKeyPos[];
 
    // default constructor define the default key
    public TranspositionCipher()
    {
        selectedKey = "megabuck";
        sortedKeyPos = new int[selectedKey.length()];
        sortedKey = selectedKey.toCharArray();
    }
 
    // Parameterized constructor define the custom key
    public TranspositionCipher(String myKey)
    {
        selectedKey = myKey;
        sortedKeyPos = new int[selectedKey.length()];
        sortedKey = selectedKey.toCharArray();
    }
 
    // To reorder data do the sorting on selected key
    public static void doProcessOnKey()
    {
        // Find position of each character in selected key and arrange it on
        // alphabetical order
        int min, i, j;
        char orginalKey[] = selectedKey.toCharArray();
        char temp;
        // First Sort the array of selected key
        for (i = 0; i < selectedKey.length(); i++)
        {
            min = i;
            for (j = i; j < selectedKey.length(); j++)
            {
                if (sortedKey[min] > sortedKey[j])
                {
                    min = j;
                }
            }
            if (min != i)
            {
                temp = sortedKey[i];
                sortedKey[i] = sortedKey[min];
                sortedKey[min] = temp;
            }
        }
        // Fill the position of array according to alphabetical order
        for (i = 0; i < selectedKey.length(); i++)
        {
            for (j = 0; j < selectedKey.length(); j++)
            {
                if (orginalKey[i] == sortedKey[j])
                    sortedKeyPos[i] = j;
            }
        }
    }
 
    // to encrypt the targeted string
    public static String doEncryption(String plainText)
    {
        int min, i, j;
        char orginalKey[] = selectedKey.toCharArray();
        char temp;
        doProcessOnKey();
        // Generate encrypted message by doing encryption using Transpotion
        // Cipher
        int row = plainText.length() / selectedKey.length();
        int extrabit = plainText.length() % selectedKey.length();
        int exrow = (extrabit == 0) ? 0 : 1;
        int rowtemp = -1, coltemp = -1;
        int totallen = (row + exrow) * selectedKey.length();
        char pmat[][] = new char[(row + exrow)][(selectedKey.length())];
        char encry[] = new char[totallen];
        int tempcnt = -1;
        row = 0;
        for (i = 0; i < totallen; i++)
        {
            coltemp++;
            if (i < plainText.length())
            {
                if (coltemp == (selectedKey.length()))
                {
                    row++;
                    coltemp = 0;
                }
                pmat[row][coltemp] = plainText.charAt(i);
            }
            else
            { // do the padding ...
                pmat[row][coltemp] = '*';
            }
        }
        int len = -1, k;
        for (i = 0; i < selectedKey.length(); i++)
        {
            for (k = 0; k < selectedKey.length(); k++)
            {
                if (i == sortedKeyPos[k])
                {
                    break;
                }
            }
            for (j = 0; j <= row; j++)
            {
                len++;
                encry[len] = pmat[j][k];
            }
        }
        String p1 = new String(encry);
        return (new String(p1));
    }
 
    // to decrypt the targeted string
    public static String doDecryption(String s)
    {
        int min, i, j, k;
        char key[] = selectedKey.toCharArray();
        char encry[] = s.toCharArray();
        char temp;
        doProcessOnKey();
        // Now generating plain message
        int row = s.length() / selectedKey.length();
        char pmat[][] = new char[row][(selectedKey.length())];
        int tempcnt = -1;
        for (i = 0; i < selectedKey.length(); i++)
        {
            for (k = 0; k < selectedKey.length(); k++)
            {
                if (i == sortedKeyPos[k])
                {
                    break;
                }
            }
            for (j = 0; j < row; j++)
            {
                tempcnt++;
                pmat[j][k] = encry[tempcnt];
            }
        }
        // store matrix character in to a single string
        char p1[] = new char[row * selectedKey.length()];
        k = 0;
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < selectedKey.length(); j++)
            {
                if (pmat[i][j] != '*')
                {
                    p1[k++] = pmat[i][j];
                }
            }
        }
        p1[k++] = '\0';
        return (new String(p1));
    }
 
    @SuppressWarnings("static-access")
    public static void main(String[] args)
    {
        TranspositionCipher tc = new TranspositionCipher();
        System.out.println("Encrypted Message is: "
                + tc.doEncryption("Sanfoundry"));
        System.out.println("Decrypted Message is: "
                + tc.doDecryption(tc.doEncryption("Sanfoundry")));
    }
}

Output:

$ javac TranspositionCipher.java
$ java TranspositionCipher
 
Encrypted Message is: f*o*n*ayn*d*Sru*
Decrypted Message is: Sanfoundry

Related posts:

Spring Boot: Customize the Jackson ObjectMapper
Java Program to Implement Sorted Singly Linked List
Java Program to find the number of occurrences of a given number using Binary Search approach
Java CyclicBarrier vs CountDownLatch
Explain about URL and HTTPS protocol
Java Program to Implement Hopcroft Algorithm
New Features in Java 13
Spring Boot - File Handling
Adding a Newline Character to a String in Java
So sánh HashMap và HashSet trong Java
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Setting Up Swagger 2 with a Spring REST API
Documenting a Spring REST API Using OpenAPI 3.0
Spring Boot - Cloud Configuration Client
Java Program to Perform the Sorting Using Counting Sort
Hướng dẫn sử dụng Java Annotation
HTTP Authentification and CGI/Servlet
Java InputStream to String
Giới thiệu SOAP UI và thực hiện test Web Service
Java Program to Implement Max-Flow Min-Cut Theorem
Java equals() and hashCode() Contracts
An Introduction to Java.util.Hashtable Class
Testing in Spring Boot
Java Program to Implement Coppersmith Freivald’s Algorithm
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Prevent Cross-Site Scripting (XSS) in a Spring Application
Java Program to subtract two large numbers using Linked Lists
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Giới thiệu Aspect Oriented Programming (AOP)
Java 8 Predicate Chain
Java Program to implement Bit Matrix
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm