Overview
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent (a=0, b=1, c=2, ..., z=25), encrypted using a simple mathematical function, and converted back to a letter.
Choose two integers a and b such that gcd(a, 26) == 1. The affine encryption function is
E(x) = a*x + b (mod 26)
The affine decryption function is
D(x) = a-1 * (x - b) (mod 26)
where a-1 is the modular multiplicative inverse of 'a' modulo 26 such that a * a-1 mod 26 == 1.
For example, let a = 5 and b = 7. Take a plain text letter x = 'H' (value is 7).
It is encrypted as a*x + b => 5*7 + 7 => 42 => 16 which is letter 'Q'.
So, the text "CODE VIBES" is encrypted as "RZWB IVMBT".
More about Affine Cipher
Aim
To write a C program to implement Affine cipher cryptography encryption and decryption algorithm.
Program Code
#include <stdio.h>
void encrypt(char msg[], int a, int b, char encrypted[])
{
int i;
for (i = 0; msg[i] != '\0'; i++) {
if (msg[i] != ' ')
encrypted[i] = (char)(((a * (msg[i] - 'A') + b) % 26) + 'A');
else
encrypted[i] = msg[i];
}
encrypted[i] = '\0';
}
void decrypt(char encrypted[], int a, int b, char decrypted[])
{
int aInv = 0, flag = 0, i;
for (i = 0; i < 26; i++) {
flag = (a * i) % 26;
if (flag == 1)
aInv = i;
}
for (i = 0; encrypted[i] != '\0'; i++) {
if (encrypted[i] != ' ')
decrypted[i] = (char)(((aInv * ((encrypted[i] + 'A') - b)) % 26) + 'A');
else
decrypted[i] = encrypted[i];
}
decrypted[i] = '\0';
}
int main()
{
char msg[100], encrypted[100], decrypted[100];
int a = 5, b = 7;
printf("Enter the message in upper case: ");
scanf("%[^\n]s", msg);
getchar();
encrypt(msg, a, b, encrypted);
printf("\nEncrypted text: %s\n", encrypted);
decrypt(encrypted, a, b, decrypted);
printf("\nDecrypted text: %s\n", decrypted);
return 0;
}
Output
No comments:
Post a Comment