apache POI为流xlsx文件创建无效签名

时间:2017-06-12 12:25:49

标签: java excel apache-poi digital-signature xmlsec

我正在尝试为我正在创建的xlsx文件创建并添加有效的常规加密签名。另外,我试图在内存中做到这一点。这似乎给我带来了麻烦。 此代码创建文件,但在Windows Excel中声明签名无效。 请注意我发送的输入流包含xlsx(内存中 - 不在文件系统中)文件,我正在将pkg对象写入输出流。

 private ByteArrayOutputStream signFile(PrivateKey key, X509Certificate x509Certificate, InputStream input) { //change to approve signed
    SignatureConfig signatureConfig = new SignatureConfig();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    signatureConfig.setKey(key);
    signatureConfig.setExecutionTime(new Date());
    ArrayList<X509Certificate> x509Certificates = new ArrayList<>(Collections.singletonList(x509Certificate));
    x509Certificates.add(x509Certificate);
    signatureConfig.setSigningCertificateChain(x509Certificates);
    OPCPackage pkg = null;
    try {
        if (input instanceof ByteArrayInputStream)
        pkg = OPCPackage.open(input);
    } catch (Exception ex) {
        logger.error("failed to open package for file, exception:",ex);
    }
    signatureConfig.setOpcPackage(pkg);

    // adding the signature document to the package
    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    try {
        si.confirmSignature();
    } catch (Exception ex) {
        logger.error("failed to confirm signature",ex);
    }
    // optionally verify the generated signature
    boolean b = si.verifySignature();
    if (b==false){
        logger.error("signature verified result:" + b);
    }

    try {
        pkg.flush();
        pkg.save(stream);
        pkg.close();
    } catch (Exception ex) {
        logger.error("failed to close package",ex);
    }

    return stream;
}

另外我有这个测试代码创建一个文件并使用OPCPackage.open(...)工作!! excel识别签名。

        SignatureConfig signatureConfig = new SignatureConfig();
        signatureConfig.setKey(aPrivate);
        ArrayList<X509Certificate> x509Certificates = new ArrayList<>();
        x509Certificates.add(x509Certificate);
        signatureConfig.setSigningCertificateChain(x509Certificates);//Collections.singletonList(x509));

        OPCPackage pkg = OPCPackage.open(filePath, PackageAccess.READ_WRITE);
        signatureConfig.setOpcPackage(pkg);

        // adding the signature document to the package
        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(signatureConfig);
        si.confirmSignature();
        // optionally verify the generated signature
        boolean b = si.verifySignature();
        assertTrue(b);
        // write the changes back to disc
        pkg.close();

0 个答案:

没有答案