Asaf Bartov
Asaf Bartov

Reputation: 55

apache POI creates invalid signature for stream xlsx file

I am trying to create and add a valid regular cryptographic signature to a xlsx file i am creating. In addition, i am trying to do it in-memory. This seems to cause problems for me. This code creates the file but in windows excel states that the signature is invalid. note that i am sending an input stream containing the xlsx (in-memory - not in file system) file, and i am writing the pkg object to the output stream.

 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;
}

in addition i have this test code which creates a file and uses OPCPackage.open(...) which works!! excel identifies the signature.

        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();

Upvotes: 1

Views: 616

Answers (0)

Related Questions