我编写了一个 RSA 算法的代码,它返回了错误的数字,这个数字恰好很大。我确信除了我不确定的一行之外,我所有的代码都是正确的。我不知道如何解决 RSA 中的私钥,只是翼翼地解决了它(我看到有人编码
d = e.modInverse(m);
其中d是私钥,e是公钥,m是(p-1)*(q-1)。我不明白 modInverse 方法是如何工作的。长话短说,你如何在同一个方程中没有两个未知数的情况下实际求解“d”(我看到了一些方程,上面写着:
d = 1/(e% m);
我没有发布结果,只是因为返回的数字与加密消息一样大。
package encryptionalgorithms;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author YAZAN Sources:
* http://introcs.cs.princeton.edu/java/78crypto/RSA.java.html
* http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html
* http://www.youtube.com/watch?v=ejppVhOSUmA
*/
public class EncryptionAlgorithms {
private static BigInteger p, q, n, m, e, r, a, b, d, encrypt, decrypt, message, userN, userE, userD;
private static BigInteger one = new BigInteger("1");
private static BigInteger badData = new BigInteger("-1");
private static BigInteger zero = new BigInteger("0");
public static void main(String[] args) {
PKE();
}
public static void PKE() { //Private Key Encryption
Scanner input = new Scanner(System.in);
Random rand1 = new Random(System.nanoTime());
Random rand2 = new Random(System.nanoTime() * 16); //to create a second obscure random number
p = BigInteger.probablePrime(1024, rand1);
q = BigInteger.probablePrime(1024, rand2);
n = p.multiply(q); // n = p * q
m = (p.subtract(one)).multiply(q.subtract(one)); // m = (p-1) * (q-1)
e = new BigInteger("65537"); //must be a prime. GCD(e,m)=1 //65537 = 2^16 + 1 // will have to make an algorith for this later
d = e.modInverse(m); //weakest link <============
// System.out.println("Public Keys:");
// System.out.println("e = " + e + " and n = " + n);
// System.out.println("Private Keys:");
// System.out.println("d = " + d + " and n = " + n);
System.out.println("please enther the message to be encrypted");
BigInteger mes = new BigInteger(input.next());
BigInteger ans = encrypt(mes, n, e);
decrypt(ans, n, d);
}
public static BigInteger encrypt(BigInteger num, BigInteger n, BigInteger e) {
encrypt = num.modPow(e, n);
System.out.println("encrypted: " + encrypt);
return encrypt;
}
public static BigInteger decrypt(BigInteger enc, BigInteger n, BigInteger d) {
decrypt = enc.modPow(d, n);
System.out.println("decrypted: " + decrypt);
return decrypt;
}
}
作为相关行的变体,我尝试了:
d = one.divide(e.mod(m));
我仍然得到不正确的结果。