1141. RSA Attack(RSA)
2024-10-21 11:57:51
越来越喜欢数论了 很有意思
先看个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)的乘积
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stdlib.h>
using namespace std;
#define N 32000
#define LL long long
int p[N+],f[N+],g;
void init()
{
int i,j;
for(i = ; i < N ; i++)
{
if(!f[i])
for(j = i+i ; j < N ; j+=i)
f[j] = ;
}
for(i = ; i < N ; i++)
if(!f[i])
p[++g] = i;
}
void exgcd(int a,int b,int &x,int &y)
{
if(b==)
{
x=;y=;return ;
}
exgcd(b,a%b,x,y);
int t = x;
x = y;
y = t-a/b*y;
}
LL expmod(int a,int b,int mod)
{
LL t;
if(b==) return %mod;
if(b==) return a%mod;
t = expmod(a,b/,mod);
t = t*t%mod;
if(b&) t = t*a%mod;
return t;
}
int main()
{
int n,k,e,i,c,a,b,x,y;
init();
cin>>k;
while(k--)
{
cin>>e>>n>>c;
for(i = ; i <= g ; i++)
if(n%p[i]==)
{
a = p[i];
b = n/p[i];
}
int o = (a-)*(b-);
exgcd(e,o,x,y);
x = x<?x+e*o:x;
LL ans = expmod(c,x,n);
cout<<ans<<endl;
}
return ;
}
最新文章
- Linux中安装NodeJs 、cnpm 、npm
- 关于页面中table中相同的列自动合并
- 【转】C语言快速幂取模算法小结
- iOS之通过PaintCode快速实现交互动画的最方便方法 未解问题
- mappedBy reference an unknown target entity property解决方法
- Hadoop及子项目备注
- fedora下vim配置
- poj 1383 Labyrinth
- React之key详解
- Java学习记录第一章
- LeetCode 48. Rotate Image(旋转图像)
- MySQL服务相关
- django restframework Serializer field
- Redis学习系列一Linux环境搭建
- Java实现经理与员工的差异
- 9 ORM-高阶补充(未完成)
- Jquery 应用积累
- Spring七大框架
- Web 漏洞分析与防御之点击劫持(三)
- 深入理解jQuery插件开发总结(四)