Java Program to Implement the Hill Cipher

This is a java program to implement hill cipher. In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. Invented by Lester S. Hill in 1929, it was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices.

Here is the source code of the Java Program to Implement the Hill Cypher. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1.  
  2. package com.sanfoundry.setandstring;
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7.  
  8. public class HillCipher
  9. {
  10.     int keymatrix[][];
  11.     int linematrix[];
  12.     int resultmatrix[];
  13.  
  14.     public void divide(String temp, int s)
  15.     {
  16.         while (temp.length() > s)
  17.         {
  18.             String sub = temp.substring(0, s);
  19.             temp = temp.substring(s, temp.length());
  20.             perform(sub);
  21.         }
  22.         if (temp.length() == s)
  23.             perform(temp);
  24.         else if (temp.length() < s)
  25.         {
  26.             for (int i = temp.length(); i < s; i++)
  27.                 temp = temp + 'x';
  28.             perform(temp);
  29.         }
  30.     }
  31.  
  32.     public void perform(String line)
  33.     {
  34.         linetomatrix(line);
  35.         linemultiplykey(line.length());
  36.         result(line.length());
  37.     }
  38.  
  39.     public void keytomatrix(String key, int len)
  40.     {
  41.         keymatrix = new int[len][len];
  42.         int c = 0;
  43.         for (int i = 0; i < len; i++)
  44.         {
  45.             for (int j = 0; j < len; j++)
  46.             {
  47.                 keymatrix[i][j] = ((int) key.charAt(c)) - 97;
  48.                 c++;
  49.             }
  50.         }
  51.     }
  52.  
  53.     public void linetomatrix(String line)
  54.     {
  55.         linematrix = new int[line.length()];
  56.         for (int i = 0; i < line.length(); i++)
  57.         {
  58.             linematrix[i] = ((int) line.charAt(i)) - 97;
  59.         }
  60.     }
  61.  
  62.     public void linemultiplykey(int len)
  63.     {
  64.         resultmatrix = new int[len];
  65.         for (int i = 0; i < len; i++)
  66.         {
  67.             for (int j = 0; j < len; j++)
  68.             {
  69.                 resultmatrix[i] += keymatrix[i][j] * linematrix[j];
  70.             }
  71.             resultmatrix[i] %= 26;
  72.         }
  73.     }
  74.  
  75.     public void result(int len)
  76.     {
  77.         String result = "";
  78.         for (int i = 0; i < len; i++)
  79.         {
  80.             result += (char) (resultmatrix[i] + 97);
  81.         }
  82.         System.out.print(result);
  83.     }
  84.  
  85.     public boolean check(String key, int len)
  86.     {
  87.         keytomatrix(key, len);
  88.         int d = determinant(keymatrix, len);
  89.         d = d % 26;
  90.         if (d == 0)
  91.         {
  92.             System.out
  93.                     .println("Invalid key!!! Key is not invertible because determinant=0...");
  94.             return false;
  95.         }
  96.         else if (d % 2 == 0 || d % 13 == 0)
  97.         {
  98.             System.out
  99.                     .println("Invalid key!!! Key is not invertible because determinant has common factor with 26...");
  100.             return false;
  101.         }
  102.         else
  103.         {
  104.             return true;
  105.         }
  106.     }
  107.  
  108.     public int determinant(int A[][], int N)
  109.     {
  110.         int res;
  111.         if (N == 1)
  112.             res = A[0][0];
  113.         else if (N == 2)
  114.         {
  115.             res = A[0][0] * A[1][1] - A[1][0] * A[0][1];
  116.         }
  117.         else
  118.         {
  119.             res = 0;
  120.             for (int j1 = 0; j1 < N; j1++)
  121.             {
  122.                 int m[][] = new int[N - 1][N - 1];
  123.                 for (int i = 1; i < N; i++)
  124.                 {
  125.                     int j2 = 0;
  126.                     for (int j = 0; j < N; j++)
  127.                     {
  128.                         if (j == j1)
  129.                             continue;
  130.                         m[i - 1][j2] = A[i][j];
  131.                         j2++;
  132.                     }
  133.                 }
  134.                 res += Math.pow(-1.0, 1.0 + j1 + 1.0) * A[0][j1]
  135.                         * determinant(m, N - 1);
  136.             }
  137.         }
  138.         return res;
  139.     }
  140.  
  141.     public void cofact(int num[][], int f)
  142.     {
  143.         int b[][], fac[][];
  144.         b = new int[f][f];
  145.         fac = new int[f][f];
  146.         int p, q, m, n, i, j;
  147.         for (q = 0; q < f; q++)
  148.         {
  149.             for (p = 0; p < f; p++)
  150.             {
  151.                 m = 0;
  152.                 n = 0;
  153.                 for (i = 0; i < f; i++)
  154.                 {
  155.                     for (j = 0; j < f; j++)
  156.                     {
  157.                         b[i][j] = 0;
  158.                         if (i != q && j != p)
  159.                         {
  160.                             b[m][n] = num[i][j];
  161.                             if (n < (f - 2))
  162.                                 n++;
  163.                             else
  164.                             {
  165.                                 n = 0;
  166.                                 m++;
  167.                             }
  168.                         }
  169.                     }
  170.                 }
  171.                 fac[q][p] = (int) Math.pow(-1, q + p) * determinant(b, f - 1);
  172.             }
  173.         }
  174.         trans(fac, f);
  175.     }
  176.  
  177.     void trans(int fac[][], int r)
  178.     {
  179.         int i, j;
  180.         int b[][], inv[][];
  181.         b = new int[r][r];
  182.         inv = new int[r][r];
  183.         int d = determinant(keymatrix, r);
  184.         int mi = mi(d % 26);
  185.         mi %= 26;
  186.         if (mi < 0)
  187.             mi += 26;
  188.         for (i = 0; i < r; i++)
  189.         {
  190.             for (j = 0; j < r; j++)
  191.             {
  192.                 b[i][j] = fac[j][i];
  193.             }
  194.         }
  195.         for (i = 0; i < r; i++)
  196.         {
  197.             for (j = 0; j < r; j++)
  198.             {
  199.                 inv[i][j] = b[i][j] % 26;
  200.                 if (inv[i][j] < 0)
  201.                     inv[i][j] += 26;
  202.                 inv[i][j] *= mi;
  203.                 inv[i][j] %= 26;
  204.             }
  205.         }
  206.         System.out.println("\nInverse key:");
  207.         matrixtoinvkey(inv, r);
  208.     }
  209.  
  210.     public int mi(int d)
  211.     {
  212.         int q, r1, r2, r, t1, t2, t;
  213.         r1 = 26;
  214.         r2 = d;
  215.         t1 = 0;
  216.         t2 = 1;
  217.         while (r1 != 1 && r2 != 0)
  218.         {
  219.             q = r1 / r2;
  220.             r = r1 % r2;
  221.             t = t1 - (t2 * q);
  222.             r1 = r2;
  223.             r2 = r;
  224.             t1 = t2;
  225.             t2 = t;
  226.         }
  227.         return (t1 + t2);
  228.     }
  229.  
  230.     public void matrixtoinvkey(int inv[][], int n)
  231.     {
  232.         String invkey = "";
  233.         for (int i = 0; i < n; i++)
  234.         {
  235.             for (int j = 0; j < n; j++)
  236.             {
  237.                 invkey += (char) (inv[i][j] + 97);
  238.             }
  239.         }
  240.         System.out.print(invkey);
  241.     }
  242.  
  243.     public static void main(String args[]) throws IOException
  244.     {
  245.         HillCipher obj = new HillCipher();
  246.         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  247.         int choice;
  248.         System.out.println("Menu:\n1: Encryption\n2: Decryption");
  249.         choice = Integer.parseInt(in.readLine());
  250.         System.out.println("Enter the line: ");
  251.         String line = in.readLine();
  252.         System.out.println("Enter the key: ");
  253.         String key = in.readLine();
  254.         double sq = Math.sqrt(key.length());
  255.         if (sq != (long) sq)
  256.             System.out
  257.                     .println("Invalid key length!!! Does not form a square matrix...");
  258.         else
  259.         {
  260.             int s = (int) sq;
  261.             if (obj.check(key, s))
  262.             {
  263.                 System.out.println("Result:");
  264.                 obj.divide(line, s);
  265.                 obj.cofact(obj.keymatrix, s);
  266.             }
  267.         }
  268.     }
  269. }

Output:

$ javac HillCipher.java
$ java HillCipher
 
Menu:
1: Encryption
2: Decryption
1
Enter the line: 
sanfoundry
Enter the key: 
sanfoundr
Result:
zmnmxfnfzdss
Inverse key:
inabzfjeq
 
Menu:
1: Encryption
2: Decryption
2
Enter the line: 
zmnmxfnfzdss
Enter the key: 
inabzfjeq
Result:
sanfoundry
Inverse key:
sanfoundr

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

👉 For weekly algorithms practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations