Search code examples
javabouncycastlepublic-key-encryptionelliptic-curvediffie-hellman

Getting ECPoint/ECPublicKeyParameters from byte[] in Bouncy Castle


So far I've managed to generate a ECDHE pair in bouncy castle's lightweight API. However I have issues trying to recreate the public key from an byte[].

Since the ECPublicKeyParameters object only has one method getQ() I am assuming thats all that is required to reconstruct the key. The other parameters such as the curve used (P-521) are kept constant.

I am doing the following:

AsymmetricCipherKeyPair kp = kpgen.generateKeyPair(); //ECDHE Key Generator

ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.getPublic();
byte[] aPubKeybytes = pubKey.getQ().getEncoded(false); //Should I set to true or false?

Unless there is another way to get the raw bytes of the public key pubKey, I don't see a way to get the bytes without invoking method getQ() which returns an ECPoint object.

My question is how to reconstruct the byte[] into a ECPoint object using bouncy castle's lightweight API. Or, better yet, how to reconstruct the whole ECPublicKeyParameter object using an byte array somehow derived from the original pubKey object.


Solution

  • To whomever it may concern I resolved this issue by using the PublicKeyFactory and SubjectPublicKeyInfoFactory to encode and decode the key.

    Using:

    byte[] key = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubKey).getEncoded();
    

    I was able to get the raw bytes of the key.

    and using:

    ECPublicKeyParameters bpubKey = (ECPublicKeyParameters)PublicKeyFactory.createKey(key);
    

    I was able to recreate the public key.