0

I was trying to understand how the RSA key generation works and therefore tried to implement it in Java. It's generating keys already, but when I'm encrypting and decrypting something using my generated keys it seems like my keys are wrong. This is my code to generate keys:

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);
}

and thats the entire class: http://pastebin.com/DDQh2Q3n

2 Answers 2

1

Here is your error:

    privateKey = publicKey.modInverse(modulo);

You need to compute this inverse mod (p-1)(q-1), which is your variable pN. So try

    privateKey = publicKey.modInverse(pN);

and see if you don't get better results.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot, that fixed it :) Another question, do you have any idea how I could optimize my code?
Optimize? What part needs optimizing?
0

Please clarify what are you trying to do. Are you trying to understand how RSA key generation works or are you simply trying to write code to generate keys for an app?

For the second, I would highly recommend not trying to write your own code to generate keys as cryptography is very easy to get wrong. Use OpenSSL/Android NDK or such.

For the first, instead of handcoding a prime calculating function, use BigInteger.probablePrime and BigInteger.nextProbablePrime(lastprime). See an implementation here: http://www.herongyang.com/Cryptography/RSA-BigInteger-RsaKeyGenerator-java.html

1 Comment

I want to understand how it works and therefore I would like to know why my code is not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.