Converting a string into X509 encoded byte array
Hello,
I'm using a diffie hellman key exchange algorithm. So I created a publickey and sent it to the server.
Here, I have a problem coz I sent the publickey as a string and I used
byte[] publicKeyBytes = publickeystring.getBytes()
to get the bytes value.
This gives me a "Invalid Key spec serverjava.security.spec.InvalidKeySpecException: Inappropriate key specification" error when I used the following code.
X509EncodedKeySpec x509KeySpec =new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFact = KeyFactory.getInstance("DH");
publicKey = keyFact.generatePublic(x509KeySpec);
There is nothing wrong with the publickeystring as when I print it out, it is fine (publickeystring = publickKey.toString()).
I suspect the problem is when the string is being converted into bytes, it's not being converted into the X509 encoding. How do I do this?
Thanks a lot,
Jose
[1042 byte] By [
Josettpata] at [2007-11-27 4:18:48]

# 2
> PublicKey.toString() does not create an X509 encoded
> version of the key. Use the getEncoded() method and
> then Base64 or Hex encode the resulting bytes if you
> cannot just store the resulting bytes.
Yup. Thanks. I know tostring() doesn't do that.
In another variation, I used the getEncoded() method to the publickey in the X509 format. This is the code I used:
String publickeystring =new String(publicKey.getEncoded());
then I converted it into bytes using:
byte[]publicKeyBytes = publickeystring.getBytes();
//Convert the public key bytes into a PublicKey object
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFact = KeyFactory.getInstance("DH");
PublicKey publicKey = keyFact.generatePublic(x509KeySpec);
Please note that I need to convert it into string in the first line coz that's how the packet is being sent.
I tried the Base 64 encoding and Hex as well. It didn't work coz the X509 Key Spec still needs the bytes in the X509 format. Not in Base 64. ( I think)
Thanks,
Jose
# 3
I don't understand what you are trying to do!
This String publickeystring =new String(publicKey.getEncoded());
is always wrong since it is almost certainly not reversible using byte[]publicKeyBytes = publickeystring.getBytes();
If you need a string then Base64 or Hex encode the result of publicKey.getEncoded() but of course you must Base64 or Hex decode the result before using it to generate an X509EncodedKeySpec .