Saturday, September 19, 2020

Hill Cipher Implementation in C

Overview

Hill cipher is developed by a mathematician named Lester S. Hill in 1929. The encryption algorithm takes m successive plain text letters an substitutes for them, m cipher text letters. The substitution is determined by m linear equations in which each character is assignd a numerical value (a=0, b=1, c=3, ..., z=25). In general terms, the Hill system can be expressed as

C = E(K, P) = P*K mod 26

P = D(K, C) = C*K-1 mod 26 = P*K*K-1 = P

More about Hill Cipher

Aim

To write a C program to implement Hill Cipher cryptography encryption and decryption algorithm.

Program Code

#include <stdio.h>
#include <ctype.h>

void encrypt(int msgVector[][1], int keyMat[][3], int cipherMat[][1])
{
    for (int i = 0; i < 3; i++) {
        cipherMat[i][0] = 0;
        for (int j = 0; j < 3; j++) {
            cipherMat[i][0] = cipherMat[i][0] + keyMat[i][j] * msgVector[j][0];
        }
        cipherMat[i][0] = cipherMat[i][0] % 26;
    }
}

void decrypt(int cipherMat[][1], int keyInv[][3], int decryptMat[][1])
{
    for (int i = 0; i < 3; i++) {
        decryptMat[i][0] = 0;
        for (int j = 0; j < 3; j++) {
            decryptMat[i][0] = decryptMat[i][0] + keyInv[i][j] * cipherMat[j][0];
        }
        decryptMat[i][0] = decryptMat[i][0] % 26;
    }
}

int main()
{
    char msg[4], encrypted[4], decrypted[4];
    int keyMat[3][3], keyInv[3][3], msgVector[3][1], cipherMat[3][1], decryptMat[3][1];

    printf("Enter 3 letter message: ");
    for (int i = 0; i < 3; i++) {
        char c;
        scanf("%c", &c);
        msg[i] = toupper(c);
    }
    msg[3] = '\0';

    for (int i = 0; i < 3; i++) {
        msgVector[i][0] = msg[i] - 'A';
    }

    printf("Enter 3x3 key matrix...\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            scanf("%d", &keyMat[i][j]);
        }
    }

    encrypt(msgVector, keyMat, cipherMat);
    for (int i = 0; i < 3; i++) {
        encrypted[i] = (char)(cipherMat[i][0] + 'A');
    }
    encrypted[3] = '\0';
    printf("\nEncrypted text: %s\n", encrypted);

    printf("\nEnter 3x3 inverse of key matrix...\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            scanf("%d", &keyInv[i][j]);
        }
    }

    decrypt(cipherMat, keyInv, decryptMat);
    for (int i = 0; i < 3; i++) {
        decrypted[i] = (char)(decryptMat[i][0] + 'A');
    }
    decrypted[3] = '\0';
    printf("\nDecrypted text: %s", decrypted);

    return 0;
}

Output



No comments:

Post a Comment

3D Transformation Graphics Program in C

Aim To write a C program to implement 3D transformations such as translation, rotation and scaling of objects. Algorithm: ·         Tr...