Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 795
Sirish Avatar asked Jul 26 '12 09:07

Sirish


People also ask

Can I extract public key from private key?

Extracting the Public Key Using ssh-keygen. The command above uses the -f option to specify the path to the private key. Then, we specify the -y option to print the public key to the console.

Is .pem a public key?

Privacy Enhanced Mail (PEM) files are a type of Public Key Infrastructure (PKI) file used for keys and certificates. PEM, initially invented to make e-mail secure, is now an Internet security standard.

Can you share public key?

Public keys have been described by some as being like a business' address on the web – it's public and anyone can look it up and share it widely. In asymmetric encryption, public keys can be shared with everyone in the system. Once the sender has the public key, he uses it to encrypt his message.


1 Answers

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.

like image 112
MrTux Avatar answered Oct 06 '22 03:10

MrTux