#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