Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Invalid RSA public key

843811Aug 1 2005 — edited Aug 2 2005
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 30 2005
Added on Aug 1 2005
1 comment
3,154 views