How to programatically sign an MS office XML docum

2020-02-07 11:42发布

Please, could someone point me in the right direction to digitally sign an MS-Office document (docx, xlsx, pptx) in Apache POI, or any other open source library?

I have already reviewed the classes under org.apache.poi.openxml4j.opc.signature but I cannot understand how I could add a signature to a document.

1条回答
做自己的国王
2楼-- · 2020-02-07 12:35

Check this sample code .. this sample code uses a file keystore PFX (PKCS12) .. Signs the Document and verify it.

 // loading the keystore - pkcs12 is used here, but of course jks & co are also valid
 // the keystore needs to contain a private key and it's certificate having a
 // 'digitalSignature' key usage
 char password[] = "test".toCharArray();
 File file = new File("test.pfx");
 KeyStore keystore = KeyStore.getInstance("PKCS12");
 FileInputStream fis = new FileInputStream(file);
 keystore.load(fis, password);
 fis.close();

 // extracting private key and certificate
 String alias = "xyz"; // alias of the keystore entry
 Key key = keystore.getKey(alias, password);
 X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias);

 // filling the SignatureConfig entries (minimum fields, more options are available ...)
 SignatureConfig signatureConfig = new SignatureConfig();
 signatureConfig.setKey(keyPair.getPrivate());
 signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
 OPCPackage pkg = OPCPackage.open(..., 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();
 assert (b);
 // write the changes back to disc
 pkg.close();

Here's the sample source : https://poi.apache.org/apidocs/org/apache/poi/poifs/crypt/dsig/SignatureInfo.html

I hope this could help!

查看更多
登录 后发表回答