您的位置:首页 > 其它

RSA算法原理

2015-10-07 17:03 369 查看
这两篇博文讲解的真是细致:
http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html http://www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html?20151007165925
上面是原文出处,可能会有一些图片显示不出来,这里再贴一个转发地址:
http://blog.jobbole.com/42699/
这里贴一个应用:

ural RSA Attack
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u


Description

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 m e = 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 Input

inputoutput
3
9 187 129
11 221 56
7 391 204

7
23
17

AC代码:

#include <iostream>
#include <cmath>
using namespace std;

//a^b%c
int fastmod(int a,int b,int c){
int num=1;
a%=c;//这里不进行初始化也是可以的

while(b>0){
if(b%2==1){
num=(num*a)%c;
}
b/=2;     //这一步将b->log2(b)
a=(a*a)%c;
}
return num;
}

int getp(int n){   //得到大于1的最小的因数
int p=2;
while(n%p!=0){
p++;
}
return p;
}
int e_gcd(int a,int b,int &x,int &y){
if(b==0){
x=1;
y=0;
return a;
}
int ans=e_gcd(b,a%b,x,y);
int temp=x;
x=y;
y=temp-a/b*y;
return ans;
}

int cal(int a,int m){
int x,y;
int gcd=e_gcd(a,m,x,y);
if(1%gcd!=0)  return -1;
x*=1/gcd;
m=abs(m);
int ans=x%m;
if(ans<=0) ans+=m;
return ans;
}

int main(){
int k;
cin>>k;
while(k--){
int e,n,c;
cin>>e>>n>>c;
int p=getp(n),q=n/p;

int d=cal(e,(p-1)*(q-1));

cout<<fastmod(c,d,n)<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: