How to programatically sign an MS office XML document with Java?

随声附和 提交于 2019-11-28 14:43:30

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!