Advertisement
midnight_sun

RSA

Jan 22nd, 2024
747
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
  3. using namespace std;
  4. typedef long long int lli;
  5. typedef pair<lli, pair<lli, lli>> pai;
  6. lli p, q, n, euler_num, e, d, m, c, rc;
  7. void choose_public_key(lli k) {
  8.     for (int i = 2; i < k; i++) {
  9.         bool flag = 0;
  10.         for (int g = 2; g <= i; g++) {
  11.             if (i % g == 0 && k % g == 0) flag=1;
  12.         }
  13.         if (!flag) cout << i << " ";
  14.     }
  15.     cout << "\n";
  16. }
  17. pai xGCD(lli a, lli b) {
  18.     if (b == 0) return { a,{1,0} };
  19.     pai ret = xGCD(b, a % b);
  20.     lli g, x, y;
  21.     g = ret.first;
  22.     tie(x, y) = ret.second;
  23.     return { g,{y,x - (a / b) * y} };
  24. }
  25. lli mod_inverse(lli a, lli mod) {
  26.     auto res = xGCD(a, mod);
  27.     if (res.first > 1) return -1;
  28.     return (res.second.first + mod) % mod;
  29. }
  30. lli power_by_divide_and_conquer(lli a, lli b, lli c) {
  31.     lli tmp = 1;
  32.     while (b) {
  33.         if (b & 1) tmp = tmp * a % c;
  34.         b /= 2;
  35.         a = a * a % c;
  36.     }
  37.     return tmp;
  38. }
  39. lli RSA_Encryption() {
  40.     return power_by_divide_and_conquer(m, e, n);
  41. }
  42. lli RSA_Decryption() {
  43.     return power_by_divide_and_conquer(c, d, n);
  44. }
  45. int main() {
  46.     fastio;
  47.     cout << "input your prime num :";
  48.     cin >> p >> q;
  49.     n = p * q; euler_num = (p - 1) * (q - 1);
  50.     choose_public_key(euler_num);
  51.     cout << "choose your public key from above: ";
  52.     cin >> e;
  53.     d = mod_inverse(e, euler_num);
  54.     cout << "your private key :" << d << "\n";
  55.     cout << "****************************\n";
  56.     cout << "your base setting\n";
  57.     cout << "p :" << p << " q :" << q << " n :" << n << " euler_num :" << euler_num << " e :" << e << " d :" << d << "\n";
  58.     cout << "input your message :";
  59.     cin >> m;
  60.     c = RSA_Encryption();
  61.     cout << c << "\n";
  62.     rc = RSA_Decryption();
  63.     cout << "****************************\n";
  64.     cout << "plain text :" << m << " RSA_Encryption :" << c << " RSA_Decryption :" << rc << "\n";
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement