这两篇博文讲解的真是细致:
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/
这里贴一个应用:
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
input | output |
---|---|
3 9 187 129 11 221 56 7 391 204 |
7 23 17 |
AC代码:
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 6 //a^b%c 7 int fastmod(int a,int b,int c){ 8 int num=1; 9 a%=c;//这里不进行初始化也是可以的 10 11 while(b>0){ 12 if(b%2==1){ 13 num=(num*a)%c; 14 } 15 b/=2; //这一步将b->log2(b) 16 a=(a*a)%c; 17 } 18 return num; 19 } 20 21 int getp(int n){ //得到大于1的最小的因数 22 int p=2; 23 while(n%p!=0){ 24 p++; 25 } 26 return p; 27 } 28 int e_gcd(int a,int b,int &x,int &y){ 29 if(b==0){ 30 x=1; 31 y=0; 32 return a; 33 } 34 int ans=e_gcd(b,a%b,x,y); 35 int temp=x; 36 x=y; 37 y=temp-a/b*y; 38 return ans; 39 } 40 41 int cal(int a,int m){ 42 int x,y; 43 int gcd=e_gcd(a,m,x,y); 44 if(1%gcd!=0) return -1; 45 x*=1/gcd; 46 m=abs(m); 47 int ans=x%m; 48 if(ans<=0) ans+=m; 49 return ans; 50 } 51 52 53 int main(){ 54 int k; 55 cin>>k; 56 while(k--){ 57 int e,n,c; 58 cin>>e>>n>>c; 59 int p=getp(n),q=n/p; 60 61 int d=cal(e,(p-1)*(q-1)); 62 63 cout<<fastmod(c,d,n)<<endl; 64 } 65 }