M.Mark
M.Mark

Reputation: 71

How to convert a hex string to a public key in java? (java.security.InvalidKeyException)

I am using EC secp160r2 for key generation. My code looks like this:

Security.insertProviderAt(new BouncyCastleProvider(), 1);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(new ECGenParameterSpec("secp160r2"), new SecureRandom());
keyPair = keyGen.generateKeyPair();

Further more I get the public key (for exchange) like following:

byte [] publicKey = keyPair.getPublic().getEncoded(); // 64 bytes
ASN1Sequence sequence = DERSequence.getInstance(publicKey);
DERBitString subjectPublicKey = (DERBitString) sequence.getObjectAt(1);
byte[] ecPublicKeyBytes = subjectPublicKey.getBytes(); // 41 bytes

and I end up with a 40 byte public key when I remove the prefix.

The problem I have is when I was to do the opposite, to get the public key out of a Hex String I receive. PubKey is a hex string of length 80. I tried generating the public key like this:

KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey generatedPublic = kf.generatePublic(new X509EncodedKeySpec(hexStringToByteArray(pubKey)));

However I end up getting an InvalidKeyException:

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: null
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePublic(ECKeyFactory.java:157)
    at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:352)
    at Main.main(Main.java:71)
Caused by: java.security.InvalidKeyException: IOException: null
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:397)
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:402)
    at jdk.crypto.ec/sun.security.ec.ECPublicKeyImpl.<init>(ECPublicKeyImpl.java:71)
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.implGeneratePublic(ECKeyFactory.java:219)
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePublic(ECKeyFactory.java:153)
    ... 2 more

Additionally here is the hex conversion method which in my case results in a 40 byte array:

public static byte[] parseHexBinary(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];

        for(int i = 0; i < hexString.length(); i += 2){
            String sub = hexString.substring(i, i + 2);
            Integer intVal = Integer.parseInt(sub, 16);
            bytes[i / 2] = intVal.byteValue();
        }
        return bytes;
    }

Any help to resolve the issue is very much appreciated!

Upvotes: 0

Views: 2041

Answers (1)

M.Mark
M.Mark

Reputation: 71

Thanks to the solution posted in the comments, I'd like to post the code that might help someone:

ECParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec("secp160r2");
ECNamedCurveSpec params = new ECNamedCurveSpec("secp160r2", ecParameterSpec.getCurve(), ecParameterSpec.getG(), ecParameterSpec.getN());
ECPoint publicPoint =  ECPointUtil.decodePoint(params.getCurve(), parseHexBinary(pubKey));
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(publicPoint, params);
KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey publicKey =  kf.generatePublic(pubKeySpec);

The code above results in a 64 Byte public key. pubKey is a public key hex string, with appended prefix. Note that 02 and 03 prefixes are used for compressed, and 04 for uncompressed keys. Elliptic Curve Cryptography Subject Public Key Information

Upvotes: 1

Related Questions