JAR中的java.security.spec.InvalidKeySpecException错误不在IDE中

时间:2018-04-13 14:23:22

标签: java jar rsa public-key

我写了一个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)

1 个答案:

答案 0 :(得分:0)

使用以下代码将输入流转换为字节数组。

InputStream keyfis = conf.getFileInputStream(publicKeyPath);
byte[] encKey = toByteArray(keyfis);
keyfis .close();

public static byte[] toByteArray(InputStream in) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    // read bytes from the input stream and store them in buffer
    while ((len = in.read(buffer)) != -1) {
        // write bytes from the buffer into output stream
        os.write(buffer, 0, len);
    }
    return os.toByteArray();
}

请参考以下网址。感谢下面的实用工具方法toByteArray的URL的作者。

https://www.techiedelight.com/convert-inputstream-byte-array-java/

如果要在同一程序中验证签名,请在验证签名之前使用相同的方法将其转换为字节数组,否则在此处也会给出错误。