#include <cstdio>
#include <stack>
#include <cmath>
#include <cstdlib>
using
namespace
std;
typedef
unsigned
long
long
int
ll;
bool
isPrime(ll a, ll n);
ll ex_gcd(ll a, ll b, ll &x1, ll &y1);
ll quick_cal(ll a, ll b, ll n);
ll getRandomNumber();
ll gcd(ll a, ll b);
int
main()
{
ll m = 1900, c = 0;
ll p = 0, q = 0, n = 0, d = 0, n_1 = 0;
ll x = 0, y = 0, e = 0;
p = getRandomNumber();
q = getRandomNumber();
n = p * q;
n_1 = (p - 1) * (q - 1);
for
(
int
i = 2; i < n_1; i++)
{
if
(gcd(n_1, i) == 1 && ex_gcd(i, n_1, x, y) == 1 && x < n_1)
{
e = i;
d = x;
}
}
printf
(
"RSA加密前的数据:%ld\n"
, m);
c = quick_cal(m, e, n);
printf
(
"RSA加密后的数据:%ld\n"
, c);
m = quick_cal(c, d, n);
printf
(
"RSA解密后的数据:%ld\n"
, m);
return
0;
}
ll quick_cal(ll a, ll b, ll n)
{
ll d = 1;
ll tmp = b;
stack<ll> s;
while
(tmp)
{
s.push(tmp % 2);
tmp /= 2;
}
while
(!s.empty())
{
d = (d * d) % n;
if
(s.top() == 1) d = (d * a) % n;
s.pop();
}
return
d;
}
ll getRandomNumber()
{
ll number =
rand
() % 1000;
while
(number < 100 || !isPrime(95, number)) number =
rand
() % 1000;
return
number;
}
ll ex_gcd(ll a, ll b, ll &x1, ll &y1)
{
if
(b == 0)
{
x1 = 1;
y1 = 0;
return
a;
}
ll x2, y2;
ll d = ex_gcd(b, a % b, x2, y2);
x1 = y2;
y1 = x2 - (a / b) * y2;
return
d;
}
bool
isPrime(ll a, ll n)
{
ll tmp = n - 1;
ll d = 1;
stack<ll> s;
ll x = 0;
while
(tmp)
{
s.push(tmp % 2);
tmp /= 2;
}
while
(!s.empty())
{
x = d;
d = (d * d) % n;
if
(d == 1 && x != 1 && x != n - 1)
return
false
;
if
(s.top() == 1) d = (d * a) % n;
s.pop();
}
if
(d != 1)
return
false
;
return
true
;
}
ll gcd(ll a, ll b)
{
return
b == 0 ? a : gcd(b, a % b);
}