# Affine cipher in C

In cryptography, an ** Affine cypher** is a kind of replacement cypher. It is a type of mono alphabetic cypher and is a rather straightforward encryption method. The reason the cypher is called

**is because it uses the mathematical idea of an affine transformation, in which a linear equation maps each plaintext letter to its matching ciphertext letter. The**

*Affine***for the letter's location in the alphabet and the**

*"multiplicative key"***, which shifts the letter's position, are the two key values in this linear equation.**

*"additive key"*Implementing the Affine cypher in a C program allows you to encrypt and decrypt communications by specifying the mathematical operations and converting plaintext into ciphertext and vice versa in a methodical manner. The function ** (ax+b)mod(26)** is used to encrypt each letter, with b representing the shift's magnitude.

### Encryption:

Every plaintext letter is associated with an integer, which is converted into an integer that is associated with a ciphertext letter using modular arithmetic. An individual letter's encryption function is:

E ( x ) = ( a x + b ) mod m

**modulus m:**size of the alphabet**a and b:**key of the cipher.**a**must be chosen such that a and m are co-prime.

### Drcryption:

The inverse functions must be applied to the ciphertext to extract the plaintext during ciphertext deciphering. The initial stage is to once more translate each letter of the ciphertext into its corresponding integer value. Performing a decryption operation:

It is the modular multiplicative inverse of an ** 'a'** modulo m, or

**D (x) = a^-1 (x - b)**mod m. It means that it fulfills the equation

**1 = a a^-1 mod m.**

### Methods for Affine Cipher in C:

**char encryptChar(char ch):** This function returns the character that is obtained after encryption from a single character, *ch*, as input. These are the tasks that it completes:

- Verifies whether the character being input is an alphabetic character.
- Establishes the capitalization or lowercase of the character.
- Takes into account the multiplicative key
and additive key b when applying the Affine cypher encryption formula to the character.*'a'* - Gives back the character that is encrypted.

**char decryptChar(char ch):** This decryption function is comparable to the ** encryptChar** function. It accepts a single character (ch) as input and outputs the character that's left over after decoding. It carries out the following roles:

- Determines if the character being entered is an alphabetic character.
- Establishes if a character is capital or lowercase.
- Determines the multiplicative key a's modular multiplicative inverse in the Affine cypher.
- Uses the inverse key to apply the Affine cypher decryption formula to the character while taking the additive key b into account.
- Gives back the decoded character.

**Example:**

Let's take an example to illustrate the use of Affine Cipher in C.

#include <stdio.h>

#include <string.h>

#include <ctype.h>

// Define the multiplicative and additive keys

int a = 5; // initializing

int b = 7;

// Function to encrypt a character using the Affine cipher

char encryptChar(char ch) {

if (isalpha(ch)) {

char base = isupper(ch) ? 'A' : 'a';

return (char)(((a * (ch - base) + b) % 26) + base);

}

else

{

return ch; // Non-alphabetic characters remain unchanged

}

}

// Function to decrypt a character using the Affine cipher

char decryptChar(char ch) {

if (isalpha(ch)) {

char base = isupper(ch) ? 'A' : 'a';

int inv_a = 0;

// Find the modular multiplicative inverse of 'a' (if it exists)

for (int i = 0; i < 26; i++) {

if ((a * i) % 26 == 1) {

inv_a = i;

break;

}

}

return (char)(((inv_a * ((ch - base - b + 26) % 26)) % 26) + base);

} else {

return ch; // Non-alphabetic characters remain unchanged

}

}

int main() {

char message[] = "TUTORIAL AND EXAMPLE";

char encrypted[100];

char decrypted[100];

// Encrypt the message

for (int i = 0; i < strlen(message); i++) {

encrypted[i] = encryptChar(message[i]);

}

encrypted[strlen(message)] = '\0';

printf("Original message: %s\n", message);

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

// Decrypt the message

for (int i = 0; i < strlen(encrypted); i++) {

decrypted[i] = decryptChar(encrypted[i]);

}

decrypted[strlen(encrypted)] = '\0';

printf("Decrypted message: %s\n", decrypted);

return 0;

}

**Output:**

Original message: TUTORIAL AND EXAMPLE

Encrypted message: YDYZOVHK HUW BSHPEKB

Decrypted message: TUTORIAL AND EXAMPLE

**Explanation:**

- First, we define the multiplicative key a and the additive key b, which are used for encryption and decryption in the
.*Affine cypher* - One character's encryption is handled by the
function. The first thing it does is verify if the character is capital or lowercase and if it is alphabetic. After that, the character is encrypted using the Affine cypher algorithm, which takes the keys*encryptChar*and*'a'*into consideration.*'b'* - Similar to
, but optimized for decoding, is the*encryptChar*function. Additionally, the decryption formula is applied, the case of the character is checked, and the modular multiplicative inverse of a character is generated.*decryptChar* - The input message is defined in the main function, arrays for the encrypted and decrypted messages are allocated, and a loop is used to process each character of the input message, carrying out encryption and decryption.
- Finally, we output the original message together with its encryption and decryption to show how the Affine cypher functions.

**Example 2:**

Let's take another example to illustrate the use of Affine Cipher in C.

#include <stdio.h>

#include <string.h>

#include <ctype.h>

// Define the multiplicative and additive keys

int a, b;

// Function to validate the multiplicative key (a) for encryption

int isMultiplicativeKeyValid(int a) {

// The multiplicative key 'a' must be coprime with 26 (i.e., GCD(a, 26) = 1)

for (int i = 1; i < 26; i++) {

if ((a * i) % 26 == 1) {

return 1; // Valid key

}

}

return 0; // Invalid key

}

// Function to encrypt a character using the Affine cipher

char encryptChar(char ch) {

if (isalpha(ch)) {

char base = isupper(ch) ? 'A' : 'a';

return (char)(((a * (ch - base) + b) % 26) + base);

} else {

return ch; // Non-alphabetic characters remain unchanged

}

}

// Function to decrypt a character using the Affine cipher

char decryptChar(char ch)

{

if (isalpha(ch))

{

char base = isupper(ch) ? 'A' : 'a';

int inv_a = 0;

// Find the modular multiplicative inverse of 'a' (if it exists)

for (int i = 1; i < 26; i++) {

if ((a * i) % 26 == 1) {

inv_a = i;

break;

}

}

return (char)(((inv_a * ((ch - base - b + 26) % 26)) % 26) + base);

}

else

{

return ch; // Non-alphabetic characters remain unchanged

}

}

int main() {

printf("Affine Cipher\n");

printf("1. Encrypt\n");

printf("2. Decrypt\n");

printf("Select an option (1/2): ");

int option;

scanf("%d", &option);

if (option != 1 && option != 2) {

printf("Invalid option. Please select 1 for encryption or 2 for decryption.\n");

return 1;

}

printf("Enter the multiplicative key (a): ");

scanf("%d", &a); // Added & to read the value

if (option == 1) {

if (!isMultiplicativeKeyValid(a)) {

printf("Invalid multiplicative key. It must be coprime with 26 (GCD(a, 26) = 1).\n");

return 1;

}

}

printf("Enter the additive key (b): ");

scanf("%d", &b); // Added & to read the value

char message[100];

char result[100];

printf("Enter the message: ");

scanf(" %[^\n]s", message);

if (option == 1)

{

// Encryption using affine cipher

for (int i = 0; i < strlen(message); i++) {

result[i] = encryptChar(message[i]);

}

result[strlen(message)] = '\0';

} else {

// Decryption

for (int i = 0; i < strlen(message); i++) {

result[i] = decryptChar(message[i]);

}

result[strlen(message)] = '\0';

}

if (option == 1) {

printf("Encrypted message: %s\n", result);

} else {

printf("Decrypted message: %s\n", result);

}

return 0;

}

**Output:**

1:

Affine Cipher

1. Encrypt

2. Decrypt

Select an option (1/2): 1

Enter the multiplicative key (a): 5

Enter the additive key (b): 7

Enter the message: TUTORIAL AND EXAMPLE

Encrypted message: YDYZOVHK HUW BSHPEKB

2:

Affine Cipher

1. Encrypt

2. Decrypt

Select an option (1/2): 2

Enter the multiplicative key (a): 5

Enter the additive key (b): 7

Enter the message: hello world

Decrypted message: apggr drcgu

**Explanation:**

- Since the multiplicative key
and the additive key b are defined as global variables, the program can access them at any time.*'a'* - The validity of the multiplicative key
for encryption is verified by the*'a'*function. An integer 'i' such that (a * i) % 26 == 1 is found to confirm that 'a' is co-prime with 26. The key is regarded as legitimate if there is such a 'i'.*isMultiplicativeKeyValid* - One character's encryption is handled by the
function. It determines whether the character is lowercase or uppercase and if it is alphabetic. Subsequently, the character is encrypted using the Affine cypher formula.*encryptChar* - Similar to
, but intended for decoding, is the decryptChar function. Additionally, the decryption formula is applied, the case of the character is checked, and the modular multiplicative inverse of a character is computed.*encryptChar* - Affine cipher's user-friendly interface is developed in the primary function:
- It presents a menu where the user can select between decryption and encryption.
- The multiplicative key, a, must be entered by the user and must be co-prime with 26 for encryption to work.
- The user is prompted to type key b, which is additive.
- The user is prompted to enter the message to be decrypted or encrypted.

## Conclusion:

This C version of the ** Affine cypher** provides a useful example of a traditional cryptography method. The Affine cypher clearly illustrates character-level encryption and decryption due to its user-friendly interface, key checking, and modular arithmetic. This code not only makes it easier to learn by doing, but it also emphasizes the need to choose the right key, specifically the requirement for a multiplicative key that is co-prime with 26. Despite its historical significance, it should be remembered that the Affine cypher is susceptible to brute force assaults and is, hence, unsuitable for secure current encryption. However, it is a useful teaching tool for comprehending the foundations of cryptography, particularly the mathematical ideas that support traditional ciphers.