rajath_pai

RSA Algorithm

Mar 16th, 2021 (edited)
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int expmod(int x, int y, int n)
  5. {
  6.     int r=1;
  7.     while(y>0)
  8.     {
  9.         if((int)(y%2)==1)
  10.             r=(r*x)%n;
  11.         x=(x*x)%n;
  12.         y=y/2;
  13.     }
  14.     return(r);
  15. }
  16.  
  17. int main(){
  18.     int p,q;
  19.     char msg[100];
  20.     cout << "Enter 2 prime numbers\n";
  21.     cin >> p >> q;
  22.     int n = p*q, z = (p-1)*(q-1);
  23.     cout << "Choose any prime number e lower than " << z << endl;
  24.     int e;
  25.     cin >> e;
  26.     int d = 1;
  27.     while((e*d)%z!=1){
  28.         d++;
  29.     }
  30.     printf("\n public key (%d,%d)",e,n);
  31.     printf("\n private key (%d,%d)",d,n);
  32.     printf("\nEnter Message\n");
  33.     cin >> msg;
  34.     cout << "\nplaintext \n";
  35.    
  36.     int plain[100],cipher[100],plain2[100];
  37.     for(int i=0; i<strlen(msg); i++){
  38.         plain[i]=msg[i];
  39.         printf("%d\t%c\n",plain[i],plain[i]);
  40.     }
  41.    
  42.     cout << "\nCiphertext after Encryption\n";
  43.     for(int i=0; i<strlen(msg); i++){
  44.         cipher[i]=expmod(plain[i],e,n);
  45.         printf("%d\t%c\n",cipher[i],cipher[i]);
  46.     }
  47.     cout << "\nplaintext after Decryption\n";
  48.     for(int i=0; i<strlen(msg); i++){
  49.         plain2[i]=expmod(cipher[i],d,n);
  50.         printf("%d\t%c\n",plain2[i],plain2[i]);
  51.     }
  52. }
  53.  
  54. /*
  55. OUTPUT
  56.  
  57. Enter 2 prime numbers
  58. 17 23
  59. Choose any prime number e lower than 352
  60. 3
  61.  
  62.  public key (3,391)
  63.  private key (235,391)
  64. Enter Message
  65. LOVE
  66.  
  67. plaintext
  68. 76  L
  69. 79  O
  70. 86  V
  71. 69  E
  72.  
  73. Ciphertext after Encryption
  74. 274 
  75. 379 {
  76. 290 "
  77. 69  E
  78.  
  79. plaintext after Decryption
  80. 76  L
  81. 79  O
  82. 86  V
  83. 69  E
  84.  
  85.  
  86. */
  87.  
Add Comment
Please, Sign In to add comment