Java:大数幂
从上面的代码可以看出,我正在尝试用Java制作RSA加密算法。问题是Java“Math.pow()”内置的幂函数不够精确,最终输出“to100”应该等于2790。我不确定我错过了什么,为此我花了几个月的时间 我也尝试过使用biginger.pow(),但没有效果。我不知道为什么BigInteger.pow()方法不起作用 我正试图得到c:Java:大数幂,java,encryption,rsa,biginteger,Java,Encryption,Rsa,Biginteger,从上面的代码可以看出,我正在尝试用Java制作RSA加密算法。问题是Java“Math.pow()”内置的幂函数不够精确,最终输出“to100”应该等于2790。我不确定我错过了什么,为此我花了几个月的时间 我也尝试过使用biginger.pow(),但没有效果。我不知道为什么BigInteger.pow()方法不起作用 我正试图得到c: c=65^17 mod 3233=2790。如这里的示例所示:如果您使用该类,这一切都非常简单 例如: import java.math.BigDecimal
c=65^17 mod 3233=2790。如这里的示例所示:如果您使用该类,这一切都非常简单 例如:
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);
由于以下几个原因,您的代码无法工作:
Math.pow
使用double
s,它只有53位的精度,不足以容纳103位的数字659974359083659205093337890625(6517)biginger#intValue
生成一个int
,它只有32位的精度,更不适合103位的数字biginger
s范围内:
biginger
的mod
操作:
BigInteger n=新的BigInteger(“65”);
大整数p=n.pow(17);
BigInteger m=新的BigInteger(“3233”);
BigInteger结果=p.mod(m);
biginger
的modPow
操作:
BigInteger n=新的BigInteger(“65”);
BigInteger e=新的BigInteger(“17”);
BigInteger m=新的BigInteger(“3233”);
BigInteger结果=n.modPow(e,m);
BigInteger
类有一个方法要做。例如,最好只使用BigInteger.valueOf(long)
而不是构造函数BigInteger(String)
@OlivierGrégoire I试图更一般,因为RSA可以使用比long
s更大的位大小(如今,2048位密钥很常见)。
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);
}