从文件获取私钥时出现问题

时间:2019-02-23 02:53:08

标签: java-security

创建PKCS8Key实例时出现错误消息,但我无法理解问题。当我打电话给

new org.apache.commons.ssl.PKCS8Key(new FileInputStream(keyPath), pass.toCharArray())

该文件也是一个正确的二进制密钥文件,该参数也不为null。但我有以下堆栈错误。

java.lang.IllegalArgumentException: Null input buffer

    at javax.crypto.Cipher.doFinal(Cipher.java:2161)
    at org.apache.commons.ssl.PKCS8Key.decrypt(PKCS8Key.java:437)
    at org.apache.commons.ssl.PKCS8Key.decryptPKCS8(PKCS8Key.java:734)
    at org.apache.commons.ssl.PKCS8Key.<init>(PKCS8Key.java:237)
    at org.apache.commons.ssl.PKCS8Key.<init>(PKCS8Key.java:105)

这对于许多.cer / .key文件效果很好,目前我只有1个带有该错误消息的文件..但对我来说,搜索尚不清楚...或了解输入错误的原因。最后,我需要向用户发送明确的异常消息。

@Test
public void sealDocument() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    String keyPath = "example.key";
    String pass = "keyPass";
    String cerPath = "example.cer";
    String fileName = "doc.txt";

    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    FileInputStream is = new FileInputStream(cerPath);
    X509Certificate cer = (X509Certificate) fact.generateCertificate(is);

    byte[] privateKeyByte = new org.apache.commons.ssl.PKCS8Key(new FileInputStream(keyPath), pass.toCharArray()).getDecryptedBytes();
    // Here is my error
    // When is creating
    KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
//        java.lang.IllegalArgumentException: Null input buffer
//
//        at javax.crypto.Cipher.doFinal(Cipher.java:2161)
//        at org.apache.commons.ssl.PKCS8Key.decrypt(PKCS8Key.java:437)
//        at org.apache.commons.ssl.PKCS8Key.decryptPKCS8(PKCS8Key.java:734)
//        at org.apache.commons.ssl.PKCS8Key.<init>(PKCS8Key.java:237)
//        at org.apache.commons.ssl.PKCS8Key.<init>(PKCS8Key.java:105)

    //Next lines can be ignored

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    // With 3 arguments I can seal
    sealDocument(privateKey, cer, fileName);

}

我的问题是错误消息是什么意思,基本上要加一个

throw new SealDocumentException('a nice error Message');

0 个答案:

没有答案