gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:24:37 24 4
gpt4 key购买 nike

我编写了一个 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));

我仍然得到不正确的结果。

最佳答案

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

    decrypt(ans, n, e);

应该是

    decrypt(ans, n, d);

一般来说,您可能会更好地使用变量名和类概念(例如实例变量)。感谢您发布完整的工作示例。

关于Java - 公私钥加密 - 如何计算RSA中的私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com