我研究了一个RSA算法的代码,它返回的是错误的数字,这恰好是巨大的。我确信我编的所有内容都是正确的,除了我不确定的一行。我不知道如何解决RSA中的私钥,只是飞了它(我看到有人代码
d = e.modInverse(m);
其中d是私钥,e是公钥,m是(p-1)*(q-1)。我不明白modInverse方法是如何工作的。长话短说,你怎么实际解决'd'而没有在同一个方程中有2个未知数(我看到一些方程式说:
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));
我的结果仍然不正确。
答案 0 :(得分:5)
decrypt(ans, n, e);
应该是
decrypt(ans, n, d);
通常,您可以使用变量名和类概念(例如实例变量)做得更好。感谢您发布完整的工作示例。