Ravi Kant Dwivedi
Ravi Kant Dwivedi

Reputation: 51

How to digitally sign the .docx file using Java

How to digitally sign the .docx file using java and signature should be embedded at the .docx file. I used Apache-poi API but I am not able to digitally sign .docx file.Which API is needed and how?

Upvotes: 5

Views: 1543

Answers (1)

kiwiwings
kiwiwings

Reputation: 3446

Although this question is quite old, I'd like to create reference answer to link to. I've adapted the e-Id applet code a while ago and signing is now possible.

Check POIs documentation for more details.

The basic code is as follows:

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

Upvotes: 3

Related Questions