3

I am having trouble converting a string which contains an RSA public key, that I have generated using SSh-keygen in cygwin, to the java.security PublicKey type.

Here is the code I am using to convert the keys

  BASE64Decoder decoder = new BASE64Decoder();
  byte[] privBytes = decoder.decodeBuffer(publicKey);
  KeyFactory keyFact = KeyFactory.getInstance("RSA");
  PublicKey testKey = keyFact.generatePublic(new X509EncodedKeySpec(publicBytes));

This code gives me this error

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

When used with this key (generated through cygwin)

AAAAB3NzaC1yc2EAAAADAQABAAABAQDQQ8K7FN3IvoLsgxyTHHidrhrp/4L1ts7fc5ooKi2lAw8pXYSseTH/ScS7qCCTTsBJ0DgdHdzjaHn8dTpOvud5Za0eiJtbPSyFmkNIwGYLXI/AnzF0sRNbSGmBeB/jQtRJBTS+1x5sVwOwGdx1jTx5m7yTmBjn9+/Hftke6UBY9dLKcRph2gpyRx1OWSFKC+mheBjpwGgapQNHFTPvhgQPp99HdGufBDiQWw4o4bIE7XIEyMpIt6KAsucbWSh67zYTaQjYzj8Bu3asCIlBy7KfdLWgrtgxddwtPjfYL3ZtGmhd3IiIwRdHQFHrJP0KbEejhJQF+2ApqFhL8yk+O3wL

However, whenever I use the Java keygenerator to create a key pair, I can convert it to a string, save it, and read it using the same method and it works. I get a public key that looks like this

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTK5ad+TnBo/N6FbPtFOtE4crvXkQUimp+gLLp
OA8QRpzTFD9zIV42695rYqmAHZRfBPA8TjEj9WXw0yRAIL3+hbHmOnLyrLfJ+5pD05B7ul83OKgV
mkLtZQacTNjX2iIeNd08ecP4+Chh/uE2dIRxHX1W00TZINySqxgW1cpjiwIDAQAB

So, I suppose my question is what is the difference between the two keys, and how can I successfully convert the first one into a usable PublicKey object?

Joshua Dixon
  • 205
  • 3
  • 11
  • You might be interested in [this question](http://stackoverflow.com/q/12749858/372643), almost a duplicate. – Bruno Aug 29 '13 at 23:00

1 Answers1

2

The first key is in ssh-rsa format. The second key is PKCS8.

You can use the -m option to ssh-keygen to generate the key in a format that java supports.

Drew MacInnis
  • 8,267
  • 1
  • 22
  • 18