【问题标题】:How to digitally sign the .docx file using Java如何使用 Java 对 .docx 文件进行数字签名
【发布时间】:2012-04-25 05:07:36
【问题描述】:

如何使用 java 对 .docx 文件进行数字签名,签名应嵌入到 .docx 文件中。我使用了 Apache-poi API,但无法对 .docx 文件进行数字签名。需要哪个 API 以及如何使用?

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

    虽然这个问题很老,但我想创建参考答案以链接到。我不久前修改了e-Id applet 代码,现在可以进行签名了。

    查看POIs documentation了解更多详情。

    基本代码如下:

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

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 2015-02-13
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多