bzoj 4522: [Cqoi2016]密钥破解 pollard_rho+欧拉定理

本文介绍了一种非对称加密算法的密钥生成过程,并提供了一种通过公钥反推私钥的方法,利用质因数分解和欧拉定理等数学原理破解加密算法。

题意

一种非对称加密算法的密钥生成过程如下:
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值