1

我正在尝试创建一个有效的常规加密签名并将其添加到我正在创建的 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();
4

0 回答 0