CPP   92

rsa cc

Guest on 14th August 2022 06:49:06 AM

  1. #include <stdio.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. long long p=89, q=97;  // factors for the modulus
  6. long long n=p*q;       // modulus
  7. long long e=49;        // encode key
  8. long long d;           // decode key
  9.  
  10. long long encode (long long x) {
  11.    long long prod = x, accu = 1;
  12.    long long expon = e;
  13.    while (expon > 0) {
  14.       if (expon % 2) { accu *= prod; accu %= n; }
  15.       prod *= prod;
  16.       prod %= n;
  17.       expon /= 2;
  18.    }
  19.    return (long long)(accu % n);
  20. }
  21.  
  22. // gets "D", the inverse of the "E" exponent used for encryption
  23. long long inverseE(long long E) {
  24.    for (long long D=1 ; D < n ; D++) {
  25.       if (((E*D) % ((p-1)*(q-1))) == 1) return D;
  26.    }
  27.    return 0;
  28. }
  29.  
  30. long long decode (long long x) {
  31.    long long prod = x, accu = 1;
  32.    long long expon = inverseE(e);
  33.    while (expon > 0) {
  34.       if (expon % 2) { accu *= prod; accu %= n; }
  35.       prod *= prod;
  36.       prod %= n;
  37.       expon /= 2;
  38.    }
  39.    return (long long)(accu % n);
  40. }
  41.  
  42. int main () {
  43.    long long out;
  44.    cout << "Inverse:" << inverseE(e) << "\n";
  45.    cout << e*inverseE(e) << " " << ((e*inverseE(e)) % ((p-1)*(q-1))) << "\n";
  46.    while (1) {
  47.       long long y = (long long)getchar();
  48.       cout << y << " " << (out=encode(y)) << " ";
  49.       cout << decode(out) << "\n";
  50.    }
  51. }

Raw Paste


Login or Register to edit or fork this paste. It's free.