Search code examples
javapublic-keyprivate-key

Get public key from private in Java


I remember do this long time ago with OpenSSL, but I want to know if it's possible and how, I've never used Cryptography on java.


Solution

  • You cannot generate either key directly from the other. It is mathematically impossible. If you had a key blob that contained both the public and private keys, you could extract either one of them with relative ease.

    EDIT, 2017: Many years and a much better understanding of crypto later, and it's now clear to me that this answer isn't really correct.

    To quote Wikipedia:

    The public key consists of the modulus n and the public (or encryption) exponent e. The private key consists of the modulus n and the private (or decryption) exponent d, which must be kept secret. p, q, and λ(n) must also be kept secret because they can be used to calculate d.

    The public modulus n can be computed as p × q. The only thing missing from a raw private key is e, but this value is usually selected as 65537, and if not you can still compute e from d and λ(n).

    However, many private key storage formats actually contain the public modulus n alongside the other components, so you can just do a direct extraction of the values.

    EDIT, 2018: Still getting downvotes for this, and rightly so! I'm leaving this answer up so people can see why I was originally wrong, and to remind myself not to be wrong in future.