CNS Practical-4

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

#define SIZE 3

// Converts key string into 3x3 key matrix
void getKeyMatrix(char* keyStr, int keyMatrix[SIZE][SIZE]) {
    for (int i = 0; i < SIZE * SIZE; i++) {
        keyMatrix[i / SIZE][i % SIZE] = tolower(keyStr[i]) - 'a';
    }
}

// Encrypts the plaintext using Hill cipher
void encrypt(char* message, int key[SIZE][SIZE], char* encrypted) {
    int len = strlen(message);
    for (int i = 0; i < len; i += SIZE) {
        for (int row = 0; row < SIZE; row++) {
            int sum = 0;
            for (int col = 0; col < SIZE; col++) {
                int ch = tolower(message[i + col]) - 'a';
                sum += key[row][col] * ch;
            }
            encrypted[i + row] = (sum % 26) + 'a';
        }
    }
    encrypted[len] = '\0';
}

int main() {
    char keyStr[10];       // 9 letters + null terminator
    char message[100];
    char encrypted[100];
    int keyMatrix[SIZE][SIZE];

    printf("Enter 9-letter key (e.g., gybnqkurp): ");
    scanf("%s", keyStr);

    if (strlen(keyStr) != 9) {
        printf("Key must be exactly 9 letters.\n");
        return 1;
    }

    printf("Enter plaintext (letters only): ");
    scanf("%s", message);

    // Pad plaintext with 'x' if necessary
    int len = strlen(message);
    while (len % SIZE != 0) {
        message[len] = 'x';
        len++;
        message[len] = '\0';
    }

    getKeyMatrix(keyStr, keyMatrix);
    encrypt(message, keyMatrix, encrypted);

    printf("Encrypted message: %s\n", encrypted);
    return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top