6

I have a requirement to read a public key using java and parse it, to check its validity, exponent, modulus or whether its valid or not. I tried the below code, and having issues. Can you please help me finding a solution for this problem?

public static void getPublicKey(String key) throws Exception {

key = key.replaceAll("-----BEGIN SSH2 PUBLIC KEY-----", "");
key = key.replaceAll("-----END SSH2 PUBLIC KEY-----", "");
KeyFactory kFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
byte pub_llave[] =  new BASE64Decoder().decodeBuffer( key ) ;
X509EncodedKeySpec spec =  new X509EncodedKeySpec(pub_llave);
PublicKey pubkey = (PublicKey) kFactory.generatePublic(spec);
}

And here is the exception:

java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DERApplicationSpecific
    at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
    at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
    at org.bouncycastle.asn1.x509.SubjectPublicKeyInfo.getInstance(Unknown Source)
Tomer
  • 17,787
  • 15
  • 78
  • 137
Sirish
  • 917
  • 3
  • 14
  • 25
  • what issues are you having? any error? – Tomer Jul 26 '12 at 09:08
  • @ftom2 - Yes. Below is the exception trace - java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DERApplicationSpecific at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source) at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source) at org.bouncycastle.asn1.x509.SubjectPublicKeyInfo.getInstance(Unknown Source) – Sirish Jul 26 '12 at 09:09
  • Please don't post code in comments, just edit your question and add it. – Tomer Jul 26 '12 at 09:10
  • 1
    ssh doesn't use X509 encoded public keys. See this question: http://stackoverflow.com/questions/3706177/how-to-generate-ssh-compatible-id-rsa-pub-from-java. – martijno Aug 15 '12 at 20:32

1 Answers1

3

SSH keys are not X.509 keys, thus it cannot work (this way).

https://jsvnserve.googlecode.com/svn/trunk/src/main/java/com/googlecode/jsvnserve/sshd/PublicKeyReaderUtil.java shows a way how to parse SSH keys.

MrTux
  • 32,350
  • 30
  • 109
  • 146