HDU 2466 A

来源:互联网 发布:淘宝十周年宣传片 编辑:程序博客网 时间:2024/05/29 19:14

题目大意:标准的RSA加密方式,这里告知你e,d,n的值,而且告诉你e的数值很小,让你尝试将p和q爆破出来,其中p小于q

首先看到题目我是懵逼的,因为数学并不是我的长项,而且大数莫不是要用c++模板?内心是拒绝的,于是乎第一次写了java程序。大体的思路如下:

首先我们明确几个RSA已知的公式:
n=pq
ed==1 (mod (p-1)*(q-1))

也就是说ed-1是(p-1)(q-1)的整数倍数,那么我在这儿就爆破,假设ed-1 可以被数i整除,那么我们假定(p-1)(q-1)=(ed-1)/i;

这时候我们可以推得
p+q=n+1-(p-1)*(q-1)
p-q=sqrt((p+q)-4*n)

当然这里需要判断!这里我们得到的所谓的p-q平方是否可以开方!用二分查找开方值,然后用开方值平方检验即可,如果上述的两个假定都满足了,说明我们找到了一组合适的值了!

当然用java的大数BigInteger喽~
BigInteger大致介绍

分享丑代码

import java.math.*;import java.util.*;import java.io.*;public class Main {    public static BigInteger sqrt(BigInteger  n){        BigInteger l=BigInteger.ZERO,r=n;        while(l.compareTo(r)<0){            BigInteger mid=(l.add(r)).divide(BigInteger.valueOf(2));            if((mid.pow(2)).compareTo(n)==0){                return mid;            }            else if((mid.pow(2)).compareTo(n)<0){                l=mid.add(BigInteger.ONE);            }            else if((mid.pow(2)).compareTo(n)>0){                r=mid.subtract(BigInteger.ONE);            }        }        return l;    }    public static boolean can_sqrt(BigInteger n){        BigInteger s=sqrt(n);        if(n.compareTo(s.pow(2))==0) return true;        else return false;    }    public static void main(String[] args){        Scanner cin=new Scanner(System.in);        BigInteger n,d,e,q,p;        BigInteger ed;        int divide,times=1;        while(cin.hasNext()){            n=cin.nextBigInteger();            d=cin.nextBigInteger();            e=cin.nextBigInteger();            if(n.compareTo(BigInteger.ZERO)==0&&d.compareTo(BigInteger.ZERO)==0&&e.compareTo(BigInteger.ZERO)==0){                break;            }            ed=(e.multiply(d)).subtract(BigInteger.ONE);            divide=0;            while(true){                divide++;                BigInteger temp1=ed.mod(BigInteger.valueOf(divide));                if(temp1.compareTo(BigInteger.ZERO)>0){                    continue;                }                temp1=ed.divide(BigInteger.valueOf(divide));                BigInteger temp2=(n.add(BigInteger.ONE)).subtract(temp1);       //p+q                if(can_sqrt((temp2.pow(2)).subtract(n.multiply(BigInteger.valueOf(4))))){                    BigInteger temp3=sqrt((temp2.pow(2)).subtract(n.multiply(BigInteger.valueOf(4))));                    q=(temp2.add(temp3)).divide(BigInteger.valueOf(2));                    p=(temp2.subtract(temp3)).divide(BigInteger.valueOf(2));                    System.out.println("Case #"+ (times++)+": " +p+ " " +q);                    break;                }            }        }    }}
0 0
原创粉丝点击