ural 1141. RSA Attack RSA算法
2016-09-21 13:40
295 查看
1141. RSA Attack
Time limit: 1.0 secondMemory 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
Onenumber 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
input | output |
---|---|
3 9 187 129 11 221 56 7 391 204 | 7 23 17 |
[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; }
相关文章推荐
- URAL 1141 计算模n的e次根
- URAL 1141(扩展欧几里德+欧拉函数)
- ****ural 1141. RSA Attack(RSA加密,扩展欧几里得算法)
- URAL 1141. RSA Attack(欧拉定理+扩展欧几里得+快速幂模)
- URAL 1141. RSA Attack RSA加密演算法
- Ural 1141. RSA Attack 扩展欧几里得算法
- URAL 1141
- URAL 1141. RSA Attack RSA加密算法
- URAL 1028. Stars
- POJ 1141 Brackets Sequence
- POJ 1141
- poj 1141 Brackets Sequence
- ural 1001 Reverse Root
- ural 1032 Find a Multiple
- ural 1066 Garland
- ural 1084. Goat in the Garden
- [解题报告]Ural 1010 Discrete Function
- Ural 1005 Stone Pilet 解题报告
- ural 1126【单调队列基础】
- 【BFS】ural 1837