Facebook
From Marshia, 1 Month ago, written in C++.
Embed
Download Paste or View Raw
Hits: 139
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int gcdExtended(int a, int b, int* x, int* y)
  6. {
  7.  
  8.     if (a == 0)
  9.     {
  10.         *x = 0, *y = 1;
  11.         return b;
  12.     }
  13.  
  14.     int x1, y1;
  15.     int gcd = gcdExtended(b % a, a, &x1;, &y1;);
  16.  
  17.  
  18.     *x = y1 - (b / a) * x1;
  19.     *y = x1;
  20.  
  21.     return gcd;
  22. }
  23.  
  24.  
  25.  
  26. int modInverse(int A, int M)
  27. {
  28.     int x, y;
  29.     int g = gcdExtended(A, M, &x, &y);
  30.     if (g != 1)
  31.         return -1;
  32.     else
  33.     {
  34.         int res = (x % M + M) % M;
  35.         return res;
  36.     }
  37. }
  38.  
  39. void decryption(string s,int ky1,int ky2)
  40. {
  41.  
  42.     string decrp="";
  43.     //cout<<"\n\n Enter cipher text : ";
  44.     //cin.ignore();
  45.     //getline(cin,s);
  46.     //int ky1,ky2;
  47.     //cout<<"Enter the first key : ";
  48.    // cin>>ky1;
  49.     //cout<<"Enter the second key : ";
  50.    // cin>>ky2;
  51.     int res=modInverse(ky1,26);
  52.     if(res==-1)
  53.     {
  54.         cout<<"Modular inverse of key 1 does not exist!!";
  55.         return;
  56.     }
  57.     char ar[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  58.  
  59.     for(int i=0; i<<"\n\n The decrypted message for the given text : "<<decrp<<endl;
  60. }
  61.  
  62. int main()
  63. {
  64.     string s,encrp="";
  65.     cout<<"Enter plain text : ";
  66.     getline(cin,s);
  67.     int ky1,ky2;
  68.     cout<<"Enter the first key : ";
  69.     cin>>ky1;
  70.     cout<<"Enter the second key : ";
  71.     cin>>ky2;
  72.     char ar[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
  73.  
  74.     int i=s[0]-'a';
  75.  
  76.     for(int i=0; i<<"\nThe encryption for the given ciphertext: "<<encrp<<endl;
  77.  
  78.     decryption(encrp,ky1,ky2);
  79.  
  80. }
  81.