您的位置:首页 > 其它

ural 1141. RSA Attack RSA算法

2016-09-21 13:40 295 查看

1141. RSA Attack

Time limit: 1.0 second
Memory limit: 64 MB

The
RSA problem is the following: given a positive integer n that is a
product of two distinct odd primes p and q, a positive integer e such
that gcd(e, (p-1)*(q-1)) = 1, and an integer c, find an integer m such
that me = c (mod n).

Input

One
number K (K <= 2000) in the first line is an amount of tests. Each
next line represents separate test, which contains three positive
integer numbers – e, n and c (e, n, c <= 32000, n = p*q, p, q –
distinct odd primes, gcd(e, (p-1)*(q-1)) = 1, e < (p-1)*(q-1) ).

Output

For each input test the program must find the encrypted integer m.

Sample

inputoutput
3
9 187 129
11 221 56
7 391 204

7
23
17

Problem Author: Michael Medvedev

[b]思路:这个主要是一个关于RSA加密算法的问题,如果想具体了解可以看阮一峰的网络日志[/b]

[b]该题的解法很简单, 首先把n分解成两个质数p, q;[/b]

[b]然后求e与(p-1)*(q-1)的逆元d[/b]

[b]最后求一发 c^d (mod n)[/b]

#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN = 32000;
int N, T;
int prime[MAXN+10], cnt = 0;
bool a[MAXN+10];
int extgcd(int a, int b, int &x, int &y){
int d = a;
if(b != 0){
d = extgcd(b, a%b, y, x);
y -= (a/b)*x;
}else {
x = 1, y = 0;
}return d;
}

int mod_inv(int a, int m){
int x, y;
extgcd(a, m, x, y);
return (m+x%m)%m;
}

void init(){
for(int i = 2; i <= MAXN; i++) a[i] = true;
for(int i = 2; i <= MAXN; i++){
if(a[i]){
prime[++cnt] = i;
}
for(int j = 1; j <= MAXN; j++){
if(prime[j]*i > MAXN) break;
a[prime[j]*i] = false;
if(i%prime[j] == 0) break;
}
}
}
int quick_pow(int a, int x, int p){
int ans = 1;
while(x > 0){
if(x&1){
x--;
ans = ans*a%p;
}
x >>= 1;
a = a*a%p;
}
return ans;
}

int main() {
//freopen("in.txt", "r", stdin);
int T;
init();
scanf("%d", &T);
while(T--){
int e, p, q, n, c, m, d;
scanf("%d%d%d", &e, &n, &c);
for(int i = 1; i <= cnt && prime[i] <= n; i++){
if(prime[i]%2 == 1 && n % prime[i] == 0){
p = prime[i];
q = n/prime[i];
break;
}
}
d = mod_inv(e, (p-1)*(q-1));
m = quick_pow(c, d, n);
printf("%d\n", m);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: