C++ Program to Implement Affine Cipher
Posted by Superadmin on August 08 2022 06:19:58

C++ Program to Implement Affine Cipher

 

 

This is a C++ Program to implement Affine Cipher. The affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. As such, it has the weaknesses of all substitution ciphers. Each letter is enciphered with the function (ax+b)mod(26), where b is the magnitude of the shift.

 

Here is source code of the C++ Program to Implement Affine Cipher. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. string encryptionMessage(string Msg)
  6. {
  7.     string CTxt = "";
  8.     int a = 3;
  9.     int b = 6;
  10.     for (int i = 0; i < Msg.length(); i++)
  11.     {
  12.         CTxt = CTxt + (char) ((((a * Msg[i]) + b) % 26) + 65);
  13.     }
  14.     return CTxt;
  15. }
  16.  
  17. string decryptionMessage(string CTxt)
  18. {
  19.     string Msg = "";
  20.     int a = 3;
  21.     int b = 6;
  22.     int a_inv = 0;
  23.     int flag = 0;
  24.     for (int i = 0; i < 26; i++)
  25.     {
  26.         flag = (a * i) % 26;
  27.         if (flag == 1)
  28.         {
  29.             a_inv = i;
  30.         }
  31.     }
  32.     for (int i = 0; i < CTxt.length(); i++)
  33.     {
  34.         Msg = Msg + (char) (((a_inv * ((CTxt[i] - b)) % 26)) + 65);
  35.     }
  36.     return Msg;
  37. }
  38. int main(int argc, char **argv)
  39. {
  40.     cout << "Enter the message: ";
  41.     string message;
  42.     cin >> message;
  43.     cout << "Message is :" << message;
  44.     cout << "\nEncrypted Message is : " << encryptionMessage(message);
  45.  
  46.     cout << "\nDecrypted Message is: " << decryptionMessage(
  47.             encryptionMessage(message));
  48. }

Output:

$ g++ AffineCipher.cpp
$ a.out
 
Enter the message: SANFOUNDRY
Message is :SANFOUNDRY
Encrypted Message is : VTGIJBGCSN
Decrypted Message is: SANFOUNDRY
------------------
(program exited with code: 0)
Press return to continue