如何使用 java 对 .docx 文件进行数字签名,并且签名应嵌入到 .docx 文件中。我使用了 Apache-poi API,但无法对 .docx 文件进行数字签名。需要哪个 API 以及如何签名?
最佳答案
虽然这个问题很老了,但我想创建引用答案来链接。我已经改编了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();
关于java - 如何使用 Java 对 .docx 文件进行数字签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309640/