Sirish
Sirish

Reputation: 937

parse and read a public key in java

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)

Upvotes: 6

Views: 5501

Answers (1)

MrTux
MrTux

Reputation: 33993

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.

Upvotes: 3

Related Questions