问题
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)
回答1:
The X509EncodedKeySpec
is expected to contain an array of bytes with the ASN.1 SubjectPublicKeyInfo
structure.
The PUB_KEY
in your example is probably the raw key value (y
in the terms of javax.crypto.spec.DHPublicKeySpec
) which is not enough to create the keyspec.
You should ask your client eother for the proper public key in the ASN.1 form to be used as input for X509EncodedKeySpec
(this is preferable) or for p
and g
parameters required for DHPublicKeySpec
.
来源:https://stackoverflow.com/questions/22676620/string-to-publickey-using-diffie-hellman-algorithm