如何解决JAR中的java.security.spec.InvalidKeySpecException错误不在IDE中的问题?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (2263)

我编写了一个RSA加密代码,在IDE上工作得很好,但是在生成JAR文件之后,出现了错误-java.security.spec.InvalidKeySpecException

private static PublicKey readPubKey()throws Exception{
    //reading public key from the path specified in the configuration file
    Config conf = new Config();
    InputStream keyfis = conf.getFileInputStream(publicKeyPath);
    byte[] encKey = new byte[keyfis.available()];
    keyfis.read(encKey);
    keyfis.close();

    // making the instance of Public key from the bytes of the Public Key
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
    java.security.KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    //---------------problem in this line of code-----------
    PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
    return publicKey;
}

问题就在眼前

PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);

异常的完整堆栈跟踪是

Exception Caught : java.security.spec.InvalidKeySpecException: 
java.security.InvalidKeyException: exponent is smaller than 3
java.security.spec.InvalidKeySpecException: 
java.security.InvalidKeyException: exponent is smaller than 3
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at com.token.TokenVerifier.readPubKey(TokenVerifier.java:55)
at com.token.TokenVerifier.verify(TokenVerifier.java:77)
at com.test.Main.main(Main.java:28)
Caused by: java.security.InvalidKeyException: exponent is smaller than 3
at sun.security.rsa.RSAPublicKeyImpl.checkExponentRange(RSAPublicKeyImpl.java:99)
at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:88)
at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:298)
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:201)
提问于
用户回答回答于

我也遇到过同样的问题,不知道怎么解决

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励