I am passing a byte[] to my method and I am trying to generate a pubKey. Looking at the error look's like i first need to decompress before generating pubKey.
How can I decode a compressed coordinate ?
private static PublicKey getPublicKeyFromBytes(byte[] pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException
{
ECPoint point = new ECPoint(new BigInteger(pubKey), BigInteger.ZERO);
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
return pk;
}
Error message:
Exception in thread "main" java.security.spec.InvalidKeySpecException: invalid KeySpec: x value invalid for SecP256R1FieldElement
at org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi.engineGeneratePublic(Unknown Source)
BigInteger
s are to be created (new BigInteger(1, ...)
) and with this theECPoint
. – BrintonBase64.getEncoder().encodeToString(pubKey)
. – SandhurstgetPublicKeyFromBytes()
triggers the posted error for an uncompressed as well as compressed X9.62 key, i.e. from the error it can't be concluded whether your data represents an uncompressed or compressed key (or even another format). In contrast,loadPubKey()
works for both, an uncompressed as well as compressed X9.62 key. Since your data triggers an error with the latter method, your data probably doesn't match the X9.62 format. Maybe it's an X.509 key. If you don't want to post the key, you can check this e.g. with lapo.it/asn1js. – Brinton