C Program to Implement the Hill Cypher

This is a C Program to implement Hill Cipher. Hill cipher is a polygraphic substitution cipher based on linear algebra.

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

  1. #include<stdio.h>
  2. #include<string.h>
  3. int main() {
  4.     unsigned int a[3][3] = { { 6, 24, 1 }, { 13, 16, 10 }, { 20, 17, 15 } };
  5.     unsigned int b[3][3] = { { 8, 5, 10 }, { 21, 8, 21 }, { 21, 12, 8 } };
  6.     int i, j;
  7.     unsigned int c[20], d[20];
  8.     char msg[20];
  9.     int determinant = 0, t = 0;
  10.     ;
  11.     printf("Enter plain text\n ");
  12.     scanf("%s", msg);
  13.     for (i = 0; i < 3; i++) {
  14.         c[i] = msg[i] - 65;
  15.         printf("%d ", c[i]);
  16.     }
  17.     for (i = 0; i < 3; i++) {
  18.         t = 0;
  19.         for (j = 0; j < 3; j++) {
  20.             t = t + (a[i][j] * c[j]);
  21.         }
  22.         d[i] = t % 26;
  23.     }
  24.     printf("\nEncrypted Cipher Text :");
  25.     for (i = 0; i < 3; i++)
  26.         printf(" %c", d[i] + 65);
  27.     for (i = 0; i < 3; i++) {
  28.         t = 0;
  29.         for (j = 0; j < 3; j++) {
  30.             t = t + (b[i][j] * d[j]);
  31.         }
  32.         c[i] = t % 26;
  33.     }
  34.     printf("\nDecrypted Cipher Text :");
  35.     for (i = 0; i < 3; i++)
  36.         printf(" %c", c[i] + 65);
  37.     return 0;
  38. }

Output:

$ gcc HillCipher.c
$ ./a.out
 
Enter plain text: SAN
 18 0 13 
Encrypted Cipher Text : R A J
Decrypted Cipher Text : S A N

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

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

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.