-1

Source: How to recover a RSA public key from a byte[] array?

This is my KeyPair generation Method:

    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime192v1");
        // Initialize the key generator and generate a KeyPair
        keyGen.initialize(ecSpec, random); // 256 bytes provides an
                                            // acceptable security level
        KeyPair keyPair = keyGen.generateKeyPair();
        // Set the public and private keys from the keyPair
        privateKey = keyPair.getPrivate();
        publicKey = keyPair.getPublic();


        System.out.println("Private and public keys:");
        System.out.println("PRIVATE: " + StringUtil.getStringFromKey(this.privateKey));
        System.out.println("PUBLIC: " + StringUtil.getStringFromKey(this.publicKey));

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
Temse
  • 11
  • 1

1 Answers1

5

In general, private keys contain enough information to rebuild public keys (it's the opposite, computing the private key from the public key, which is hopefully not feasible). In the case of a normal RSA private key in Java, you would use java.lang.security.KeyFactory.getKeySpec() to obtain a java.security.spec.RSAPrivateCrtKeySpec instance, that contains, among other things, the modulus (getModulus()) and the public exponent (getPublicExponent()), i.e. the two elements of the public key.

Now, of course, your code is not a generator for an RSA key pair, but for an elliptic curve key pair, which is an altogether different animal. There again, though, the private key contains enough information to recompute the public key. However, this involves an elliptic curve multiplication, an operation which is doable (that's the kind of operation used when signing or verifying an ECDSA signature) but for which I am not sure there is a ready-to-use API in Java.

In any case, when you generate the private key, you actually generate a key pair with both the private key and the public key. If you store a copy of the public key along with the private key, then you do not have to worry about recomputing the public key.

Thomas Pornin
  • 72,986
  • 14
  • 147
  • 189
  • Bouncy Castle API (not so much the provider) now contains a pretty good EC API that of course handles multiplication (it was heavily refactored in the past). It is a software only provider after all. – Maarten Bodewes Jan 30 '18 at 14:19