1141. RSA Attack(RSA)

1141

越来越喜欢数论了 很有意思

先看个RSA的介绍

RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对 密钥,使用其中一个加密,则需要用另一个才能解密。
RSA的算法涉及三个参数,n、e1、e2。
其中, n是两个大质数p、 q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。
e1和e2是一对相关的值,e1可以任意取,但要求e1与(p-1)*(q-1) 互质;再选择e2,要求(e2*e1)mod((p-1)*(q-1))=1。
(n,e1),(n,e2)就是密钥对。其中 (n,e1)为 公钥(n,e2)为私钥。[1]
RSA加解密的算法完全相同,设A为明文,B为密文,则:A=B^e2 mod n;B=A^e1 mod n;(公钥加密体制中,一般用公钥加密,私钥解密)
e1和e2可以互换使用,即:
A=B^e1 mod n;B=A^e2 mod n;
这题就是一个RSA求密文的算法
因为(e2*e1)mod((p-1)*(q-1))=1。 所以 e2*e1+k*(p-1)*(q-1)  = 1 运用扩展欧几里得可以求出e2 K 当然K是没有用的 再快速幂求出(c,e2)%n=B
如果e2为负值 就加上e1与(p-1)*(q-1)的乘积
 1 #include <iostream>

 2 #include<cstdio>

 3 #include<cstring>

 4 #include<algorithm>

 5 #include<stdlib.h>

 6 using namespace std;

 7 #define N 32000

 8 #define LL long long

 9 int p[N+10],f[N+10],g;

10 void init()

11 {

12     int i,j;

13     for(i = 2; i < N ; i++)

14     {

15         if(!f[i])

16         for(j = i+i ; j < N ; j+=i)

17         f[j] = 1;

18     }

19     for(i = 2; i < N ; i++)

20     if(!f[i])

21     p[++g] = i;

22 }

23 void exgcd(int a,int b,int &x,int &y)

24 {

25     if(b==0)

26     {

27         x=1;y=0;return ;

28     }

29     exgcd(b,a%b,x,y);

30     int t = x;

31     x = y;

32     y = t-a/b*y;

33 }

34 LL expmod(int a,int b,int mod)

35 {

36     LL t;

37     if(b==0) return 1%mod;

38     if(b==1) return a%mod;

39     t = expmod(a,b/2,mod);

40     t = t*t%mod;

41     if(b&1) t = t*a%mod;

42     return t;

43 }

44 int main()

45 {

46     int n,k,e,i,c,a,b,x,y;

47     init();

48     cin>>k;

49     while(k--)

50     {

51         cin>>e>>n>>c;

52         for(i = 1 ; i <= g ; i++)

53         if(n%p[i]==0)

54         {

55             a = p[i];

56             b = n/p[i];

57         }

58         int o = (a-1)*(b-1);

59         exgcd(e,o,x,y);

60         x = x<0?x+e*o:x;

61         LL ans = expmod(c,x,n);

62         cout<<ans<<endl;

63     }

64     return 0;

65 }
View Code

 

你可能感兴趣的:(rsa)