解析并读取java中的公钥

时间:2012-07-26 09:00:02

标签: java bouncycastle public-key-encryption

我需要使用java读取公钥并解析它,检查其有效性,指数,模数或是否有效。我尝试了以下代码,并遇到了问题。能帮我找到解决这个问题的方法吗?

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);
}

以下是例外:

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)

1 个答案:

答案 0 :(得分:2)

SSH密钥不是X.509密钥,因此它无法工作(这种方式)。

https://jsvnserve.googlecode.com/svn/trunk/src/main/java/com/googlecode/jsvnserve/sshd/PublicKeyReaderUtil.java显示了解析SSH密钥的方法。