Java RSA密钥生成

时间:2014-07-16 23:47:09

标签: java encryption rsa

我试图理解RSA密钥生成是如何工作的,因此试图用Java实现它。它已经生成了密钥,但是当我使用生成的密钥加密和解密某些内容时,我的密钥似乎是错误的。这是我生成密钥的代码:

public void generateNewKeypair(int bit) {
    BigInteger[] primes = generatePrimes(2, bit / 2);
    BigInteger p = primes[0];
    BigInteger q = primes[1];
    modulo = q.multiply(p);
    BigInteger pN = (q.subtract(BigInteger.valueOf(1))).multiply(p.subtract(BigInteger.valueOf(1)));
    publicKey = BigInteger.ZERO;
    while (publicKey.equals(BigInteger.ZERO)) {
        BigInteger rnd = new BigInteger(pN.bitLength(), random);
        if (rnd.compareTo(pN) <= 0 && rnd.gcd(pN).equals(BigInteger.ONE)) {
            publicKey = rnd;
        }
    }
    privateKey = publicKey.modInverse(modulo);
}

就是整个班级:http://pastebin.com/DDQh2Q3n

2 个答案:

答案 0 :(得分:1)

这是您的错误:

    privateKey = publicKey.modInverse(modulo);

您需要计算此逆mod(p-1)(q-1),这是您的变量pN。所以试试

    privateKey = publicKey.modInverse(pN);

看看你是否得到了更好的结果。

答案 1 :(得分:0)

请说明你想做什么。您是在尝试了解RSA密钥生成的工作原理,还是只是尝试编写代码来为应用程序生成密钥?

对于第二种情况,我强烈建议不要尝试编写自己的代码来生成密钥,因为加密很容易出错。使用OpenSSL / Android NDK等。

对于第一个,使用BigInteger.probablePrime和BigInteger.nextProbablePrime(lastprime)而不是手动编码主要计算函数。请参阅此处的实施:http://www.herongyang.com/Cryptography/RSA-BigInteger-RsaKeyGenerator-java.html