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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With