Java:Power Massive Numbers

时间:2017-11-06 11:32:16

标签: java encryption rsa biginteger

import java.math.BigDecimal;
import java.math.BigInteger;
public class RSAEncryption {
public static void main(String[] args){
//STAGE ONE AND TWO
int p=61;
int q=53;
//STAGE THREE
Integer pq=p*q;
//STAGE FOUR
int pTotient=p-1;
int qTotient=q-1;
//STAGE FIVE
//  int finalTotient=pTotient*qTotient;
int finalTotient=780;
//STAGE SIX AND SEVEN
int e=0;
if((p>17)||(q>17)){
    e=17;
}else{
    e=7;
}
//STAGE EIGHT AND NINE
int d=0;
int count=0;
while ((e*d%finalTotient)!=1){
    d=d+1;
    count=count+1;
}
//STAGE TEN
int ed=e*d;
System.out.println("p = "+p);
System.out.println("q = "+q);
System.out.println("pq = "+pq);
System.out.println("final totient = "+finalTotient);
System.out.println("calculation of ed = "+ed);
System.out.println("d = "+d);
//ENCRYPTION
int message=65;
//PUBLIC KEY
int result00 = (int)Math.pow(message, e);
System.out.println(result00);
int testing00=result00%3233;
System.out.println(testing00);
BigInteger dd00=new BigInteger("65");
BigInteger test00=dd00.pow(17);
System.out.println("BigInteger Power Calc: "+test00);
int to100=test00.intValue();
int finalt=to100%3233;
System.out.println(to100);

从上面的代码中你可以看到我试图用Java制作RSA加密算法。问题在于使用Java构建的幂函数" Math.pow()"不够精确,最终输出" to100"应该等于2790.我不确定我错过了什么并花了几个月的时间。

我也尝试过使用BigInteger.pow(),但无济于事。我不确定为什么BigInteger.pow()方法不起作用。

我试图获得c:

c = 65 ^ 17 mod 3233 = 2790.如此处示例中所示:https://en.wikipedia.org/wiki/RSA_(cryptosystem)

2 个答案:

答案 0 :(得分:2)

如果您使用BigInteger类,这一切都非常简单。

示例:

private static final BigInteger ONE = BigInteger.ONE;

public static void main(String[] args) {

    BigInteger p = BigInteger.valueOf(61);
    BigInteger q = BigInteger.valueOf(53);
    BigInteger pq = p.multiply(q);
    BigInteger finalTotient = p.subtract(ONE).multiply(q.subtract(ONE));
    BigInteger e = BigInteger.valueOf(17);
    BigInteger d = e.modInverse(finalTotient);
    BigInteger message = BigInteger.valueOf(65);
    BigInteger encrypted = message.modPow(e, pq);
    BigInteger decrypted = encrypted.modPow(d, pq);
}

答案 1 :(得分:1)

您的代码由于以下几个原因而无法运作:

  1. Math.pow使用double s,它只有53位精度,不足以容纳103位数字6,599,743,590,836,592,050,933,837,890,625(65 17
  2. BigInteger#intValue产生一个int,它只有32位的精度,更适合103位的数字。
  3. 您有两种选择,两种选择都涉及BigInteger

    1. 缓慢的方式:执行BigInteger mod操作:

      BigInteger n = new BigInteger("65");
      BigInteger p = n.pow(17);
      BigInteger m = new BigInteger("3233");
      BigInteger result = p.mod(m);
      
    2. 快捷方式:执行BigInteger&#39} modPow操作:

      BigInteger n = new BigInteger("65");
      BigInteger e = new BigInteger("17");
      BigInteger m = new BigInteger("3233");
      BigInteger result = n.modPow(e, m);