I've generated public-private keys using ssh-keygen -t rsa
Following is my public key
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDtbGPZjdnMWk8lJ/CdaBZROCtNk8H+Ru4keC7DK55q2t2ISRgjBaR4qZnWezAA2iJX3cwq2ulfwCPmyoc0G180lUEMDkZkeuWzyvwWjZIo0cehN2j28evgpZadfe+NxYYqQ2f7/3eJ+3IwT4EE6WmzaYjsYXloilJLVJFBbPkdy+1xnHAa1RXsdDNjMPQ9d9PSdr9BYlph21lzflk5wdBxXnLxzUD3mb3j0cCMrIl7IF2CbkKnBC4VFZahRRyJLBWvXvcxXR7Pspv6/WUE2GsZZ3GynAhS7LuHk7NKmB13+lQFejDGO4yVsXQLw7dg+JsIs4h3JkindgJRUytQq7lZ user@Ganesh-VirtualBox
This is my code which gets me the public key
public static PublicKey getPublicKey(String filename)
throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec =
new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
I'm passing correct filename to this method. The line kf.generatePublic(spec)
is throwing error as shown below.
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
Why am I getting this error?