【问题标题】:How to programatically sign an MS office XML document with Java?如何使用 Java 以编程方式签署 MS Office XML 文档?
【发布时间】:2023-04-11 01:37:01
【问题描述】:

请,有人能指出我在 Apache POI 或任何其他开源库中对 MS-Office 文档(docx、xlsx、pptx)进行数字签名的正确方向吗?

我已经查看了 org.apache.poi.openxml4j.opc.signature 下的类,但我不明白如何在文档中添加签名。

【问题讨论】:

  • Open Office XMLOffice Open XML 是不同的。前者由 Sun Micro System 开发,后者由 Microsoft 开发。

标签: java ms-office digital-signature


【解决方案1】:

检查此示例代码 .. 此示例代码使用文件密钥库 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

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多