Java - 公钥 - 私钥加密 - 如何在RSA中计算私钥

Yaz*_*zra 2 java rsa biginteger public-key-encryption

我研究了一个RSA算法的代码,它返回了错误的数字,这恰好是巨大的.我确信我编的所有内容都是正确的,除了我不确定的一行.我不知道如何解决RSA中的私钥,只是飞过它(我看到有人代码

d = e.modInverse(m);

其中d是私钥,e是公钥,m是(p-1)*(q-1).我不明白modInverse方法是如何工作的.长话短说,你如何在没有2个未知数的情况下实际解决'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;
    }
}
Run Code Online (Sandbox Code Playgroud)

作为相关行的变体,我试过:

d = one.divide(e.mod(m));

而且我的结果仍然不正确.

Jam*_*olk 5

哈哈,你要踢自己.你做的一切都是正确的,除了这个小小的怪物:

    decrypt(ans, n, e);
Run Code Online (Sandbox Code Playgroud)

应该

    decrypt(ans, n, d);
Run Code Online (Sandbox Code Playgroud)

通常,您可以使用变量名称和类概念(如实例变量)做得更好.感谢您发布完整的工作示例.