I have a Public key string (128 bytes byte to hex processed) given by my client. I need to generate shared key using the private key and Public key given by client. I'm getting below exception while converting the String to Public key. I tried decoding/encoding the bytes, no improvement. I have the following code.
// This is a sample key.
private static final String PUB_KEY = "0DC1B7102DE3F6785A284ABFCA1822A6B59C947B5F2FAAE" + "672D8EE29C3D801BC153777CD3AF5478FD25C234C50BBABF8CD5215A8F1CB19B0B4A24FD5E9" + "412264646E2A06FCB5929FFBE196A1BD58B9927424C3B3D0388FDDA15FD1FF1C3E7600A629E" +
"B3F0B38B85CCCE03D44CF8D53B2E4E5EFD54E991CE92E55B10FCCD79F04";
public static void main(String[] argv) throws Exception {
PublicKey key = getKey(h2b(PUB_KEY));
}
private static PublicKey getKey(final byte[] pubKey) throws Exception {
final KeyFactory keyFactory = KeyFactory.getInstance("DH");
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKey);
return keyFactory.generatePublic(keySpec); // THROWS EXCEPTION
}
private static byte[] h2b(String hex) {
if ((hex.length() & 0x01) == 0x01)
throw new IllegalArgumentException();
byte[] bytes = new byte[hex.length() / 2];
for (int idx = 0; idx < bytes.length; ++idx) {
int hi = Character.digit((int) hex.charAt(idx * 2), 16);
int lo = Character.digit((int) hex.charAt(idx * 2 + 1), 16);
if ((hi < 0) || (lo < 0))
throw new IllegalArgumentException();
bytes[idx] = (byte) ((hi << 4) | lo);
}
return bytes;
}
Throws follwoing excetpion. Any help to solve this?
Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DHKeyFactory.java:87)