Guest User

RSA

a guest
Dec 13th, 2011
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. struct par {
  7.     int r,t;
  8. };
  9.  
  10. par euclid(int a, int b) {
  11.     int x = a;
  12.     int y = b;
  13.     int t0 = 0;
  14.     int t1 = 1;
  15.     int r = b;
  16.     int t = 1;
  17.     int q;
  18.     printf("q: -\tr: -\tt: -\tx: %d\ty: %d\tt0: %d\tt1: %d\t x mod y:%d\n",x,y,t0,t1,x%y);
  19.     while ((x%y) != 0) {
  20.         r = x % y;
  21.         q = x / y;
  22.         t = (t0 - q*t1) % a;
  23.         x = y;
  24.         y = r;
  25.         t0 = t1;
  26.         t1 = t;
  27.         printf("q: %d\tr: %d\tt: %d\tx: %d\ty: %d\tt0: %d\tt1: %d\tx mod y: %d\n",q,r,t,x,y,t0,t1,x%y);
  28.     }
  29.     par p;
  30.     p.r = r;
  31.     p.t = t;
  32.     return p;
  33. }
  34.  
  35. // return b^e mod m
  36. int modular_pow(int base, int exponent, int modulus) {
  37.     int result = 1;
  38.     while (exponent > 0) {
  39.         if (exponent & 1)
  40.             result = (result * base) % modulus;
  41.         exponent >>= 1;
  42.         base = (base * base) % modulus;
  43.     }
  44.     return result;
  45. }
  46.  
  47.  
  48. int main () {
  49.     int a,b,n,x;
  50.     cout << "Kérem fi(n)-t" << endl;
  51.     cin >> a;
  52.     cout << "Kérem e-t" << endl;
  53.     cin >> b;
  54.     cout << "Kérem n-t" << endl;
  55.     cin >> n;
  56.     par p = euclid(a,b);
  57.     cout << "r: " << p.r << endl;
  58.     cout << "t: " << p.t << endl;
  59.     int res = (b* p.t) % a ;
  60.     if (res < 0)
  61.         res += a;
  62.         res %= a;
  63.     cout << "Ellenőrzés: " << b << "*" <<  p.t <<" mod (" << a << ") = " << res << endl;
  64.     while (!cin.eof()) {
  65.         cout << "Kérem a titkosítandó üzenetet" << endl;
  66.         cin >> x;
  67.         int y = modular_pow(x, b, n);
  68.         cout << "y = x^e mod n: " << y << endl;
  69.         int z = modular_pow(y, p.t, n);
  70.         cout << "x = y^d mod n: " << z << endl;
  71.     }
  72.     return 0;
  73. }
  74.  
  75.  
  76.  
  77. /*
  78. INPUT:
  79. a (egyik szám)
  80. b (másik szám)
  81. OUTPUT: r (a és b legnagyobb közös osztója)
  82. t (az a legkisebb szám melyre t*b mod a = r)
  83. // feltesszük, hogy a > b
  84. // (ellenkez ̋ esetben felcseréljük a bementeket)
  85. o
  86. x = a
  87. y = b
  88. t0 = 0
  89. t1 = 1
  90. r = b
  91. t = 1
  92. WHILE (x mod y) != 0
  93. q = x div y // maradékos osztás eredménye
  94. r = x mod y // és maradéka
  95. t = (t0 - q*t1) mod a
  96. x = y
  97. y = r
  98. t0 = t1
  99. t1 = t
  100. ENDWHILE
  101. RETURN r, t
  102. */
  103.  
  104.  
Advertisement
Add Comment
Please, Sign In to add comment