Search code examples
javabouncycastlejceelliptic-curve

How does one convert a public EC code point and curve name into a PublicKey?


I have two 32 byte long byte arrays representing the X and Y values for an EC Public Key. I know that the curve is the named curve "prime256v1".

How can I turn that into a Java PublicKey object?

The JCE appears to provide no facilities whatsoever to use named curves.

Bouncycastle's example code does not appear to compile with any version of bouncycastle I can find.

WTF?


Solution

  • It turns out that there is, in fact, another way to do this. The AlgorithmParameters class can apparently be used to translate an ECGenParameterSpec, with a named curve, into an ECParameterSpec object that you can use with a KeyFactory to generate a PublicKey object:

    ECPoint pubPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));
    AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "SunEC");
    parameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(pubPoint, ecParameters);
    KeyFactory kf = KeyFactory.getInstance("EC");
    return (ECPublicKey) kf.generatePublic(pubSpec);