请问,有人能指出我在Apache POI或任何其他开源库中对MS-Office文档(docx,xlsx,pptx)进行数字签名的正确方向吗?
我已经查看了org.apache.poi.openxml4j.opc.signature下的类,但我无法理解如何在文档中添加签名。
答案 0 :(得分:2)
检查此示例代码..此示例代码使用文件密钥库PFX(PKCS12)..签署文档并验证它。
// 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();
以下是示例来源:https://poi.apache.org/apidocs/org/apache/poi/poifs/crypt/dsig/SignatureInfo.html
我希望这可以提供帮助!