I'm using SUNJce (JDK 1.5) to encrypt and decrypt with RSA algorithm, when i run the code as standalone (with my IDE), it works fine. but when i JAR my application and run the code,
Same thing with BouncyCastle provider too.
It gives
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.secu
rity.InvalidKeyException: Invalid RSA public key
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(Unknown Source)
at java.security.KeyFactory.generatePublic(Unknown Source)
Following is the piece of code which reads the Public key
private static PublicKey readPublicKey()
throws Exception {
String fl = "pubKey.dat";
InputStream fis = RSACryption.class.getResourceAsStream(fl);
int kl = fis.available();
byte[] kb = new byte[kl];
fis.read(kb);
fis.close();
String pubKey = encodeBASE64(kb);
return getPublicKeyFromString(pubKey);
}
public static PublicKey getPublicKeyFromString(String key) throws Exception
{
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(key));
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return publicKey;
}
Exception is thrown in
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
The same methodology i had used before for other algorithms (Blowfish/ 3DES), all were fine.
The main idea is keeping the public key file in the jar and using getResourceAsStream.
Need Help
Thanks in advance