题意
一种非对称加密算法的密钥生成过程如下:
1. 任选两个不同的质数 p ,q
2. 计算 N=pq , r=(p-1)(q-1)
3. 选取小于r ,且与 r 互质的整数 e
4. 计算整数 d ,使得 ed≡1 mod r
5. 二元组 (N,e) 称为公钥,二元组 (N,d) 称为私钥
当需要加密消息 n 时(假设 n 是一个小于 N 整数,因为任何格式的消息都可转为整数表示),使用公钥 (N,e),按照
n^e≡c mod N
运算,可得到密文 c 。
对密文 c 解密时,用私钥 (N,d) ,按照
c^d≡n mod N
运算,可得到原文 n 。算法正确性证明省略。
由于用公钥加密的密文仅能用对应的私钥解密,而不能用公钥解密,因此称为非对称加密算法。通常情况下,公钥由消息的接收方公开,而私钥由消息的接收方自己持有。这样任何发送消息的人都可以用公钥对消息加密,而只有消息的接收方自己能够解密消息。
现在,你的任务是寻找一种可行的方法来破解这种加密算法,即根据公钥破解出私钥,并据此解密密文。
输入文件内容只有一行,为空格分隔的j个正整数e,N,c。N<=2^62,c
分析
一开始还以为是大数论题,其实只要把n分解质因数然后模拟就好了。
这里求逆元可以用欧拉定理。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
LL n,e,c,a[105];
int prime[9]={2,3,5,7,11,13,17,19,23},tot;
LL mul(LL x,LL y,LL mo)
{
LL ans=(x*y-(LL)((double)x*y/mo+0.1)*mo)%mo;
ans+=ans<0?mo:0;
return ans;
}
LL ksm(LL x,LL y,LL mo)
{
LL ans=1;
while (y)
{
if (y&1) ans=mul(ans,x,mo);
x=mul(x,x,mo);y>>=1;
}
return ans;
}
bool MR(LL n)
{
if (n==2) return 1;
if (n%2==0) return 0;
LL w=n-1;int lg=0;
while (w%2==0) w/=2,lg++;
for (int i=0;i<9;i++)
{
if (n==prime[i]) return 1;
LL x=ksm(prime[i],w,n);
for (int j=0;j<lg;j++)
{
LL y=mul(x,x,n);
if (x!=1&&x!=n-1&&y==1) return 0;
x=y;
}
if (x!=1) return 0;
}
return 1;
}
LL gcd(LL x,LL y)
{
if (!y) return x;
else return gcd(y,x%y);
}
LL rho(LL n)
{
LL c=rand()*rand()%(n-1)+1,x1=rand()*rand()%n,x2=x1,k=1,p=1;
for (int i=1;p==1;i++)
{
x1=(mul(x1,x1,n)+c)%n;
if (x1==x2) return 1;
p=gcd(n,abs(x1-x2));
if (i==k) k<<=1,x2=x1;
}
return p;
}
void divi(LL n)
{
if (n==1) return;
if (MR(n)) {a[++tot]=n;return;}
LL p=1;
while (p==1) p=rho(n);
divi(p);divi(n/p);
}
LL get_phi(LL n)
{
tot=0;divi(n);LL ans=n;
sort(a+1,a+tot+1);tot=unique(a+1,a+tot+1)-a-1;
for (int i=1;i<=tot;i++) ans=ans/a[i]*(a[i]-1);
return ans;
}
int main()
{
scanf("%lld%lld%lld",&e,&n,&c);
divi(n);
LL r=(a[1]-1)*(a[2]-1),d=ksm(e,get_phi(r)-1,r),ans=ksm(c,d,n);
printf("%lld %lld",d,ans);
return 0;
}