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

3
我曾经写了一个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;
    }
}

作为对问题的一种替代方案,我尝试了:

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

但是我仍然得到了错误的结果。

1个回答

6

哈哈,你将会自己踢自己。你做的一切都是正确的,除了这个微小的错误:

    decrypt(ans, n, e);

应该是

    decrypt(ans, n, d);

总的来说,你可能可以在变量名和类概念(例如实例变量)方面做得更好。赞扬你发布了一个完整的工作示例。


哈哈,谢谢。但是现在无论你输入什么原始消息,它都会始终返回1作为解密后的消息。 - YazanLpizra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接