Ganesh Satpute
Ganesh Satpute

Reputation: 3951

Encryption using public-private keys

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?

Upvotes: 0

Views: 468

Answers (1)

hagrawal7777
hagrawal7777

Reputation: 14668

Typically public keys are required in X.509 format and private keys are required in PKCS#8 format. So, whenever you are dealing with public/private keys, you need to make sure that they are in appropriate format.

Read below from Oracle docs

So, first you need a key specification. You can obtain one via the following, assuming that the key was encoded according to the X.509 standard, which is the case, for example, if the key was generated with the built-in DSA key-pair generator supplied by the SUN provider:

Main error you are getting is InvalidKeyException which says:

This is the exception for invalid Keys (invalid encoding, wrong length, uninitialized, etc).

Now in you case it is the invalid encoding which is resulting this error because you are using the generated public key in clear and not making it compatible with X509EncodedKeySpec. So, to fix you problem first encode your public key as per X.509 standard so that you can use in X509EncodedKeySpec

Upvotes: 1

Related Questions