0

I am working on a project with a requirement that needs to sign non PDF files like .docx, .xlsx, etc. I made a research of libraries and ways to sign these files, I found the Apache POI library and a sample code to sign files. After making some changes in the code to adapt with the project (it's important to say that the private key is the same that I use to sign PDF files with itext library) this is the resulting code:

PrivateKey key = (PrivateKey) ks.getKey(alias, pass);
X509Certificate certificado = (X509Certificate) ks.getCertificate(alias);

SignatureConfig signatureConfig = new SignatureConfig();
signatureConfig.setKey(key);
signatureConfig.setSigningCertificateChain(Collections.singletonList(certificado));
OPCPackage pkg = OPCPackage.open("DOCUMENT.docx", PackageAccess.READ_WRITE);
signatureConfig.setOpcPackage(pkg);

SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(signatureConfig);
si.confirmSignature();
boolean b = si.verifySignature();
assert (b);
pkg.close();

However, I am getting the following exception when the code calls the confirmSignature() method:

GRAVE: ERROR-----------------------------org.apache.poi.EncryptedDocumentException: java.security.InvalidKeyException: Private keys must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding

The exception says that there is a problem with the Private Key, but like I said before is the same key for PDF files. The return value of the method key.getAlgorithm() is "RSA".

Any idea what may be the problem? or any other library to sign non pdf documents.

  • Does this webpage help you? [Apache POI - Encryption support](http://poi.apache.org/encryption.html) – Nakarukatoshi Uzumaki Oct 19 '21 at 15:52
  • i find the error message clear: (although it is "the right") key has wrong "format" (`must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding`)! ... https://stackoverflow.com/q/906402/592355 – xerx593 Oct 19 '21 at 15:55
  • 1st idea: if it's not a PKCS#8 encoded or RSA private key - what is it? 2nd: "Grave error" looks like j2ee ... please try your code standalone and not as part of a web application first 3rd: if you want support on this, you could provide me a dummy keystore with the same error and I could try to get it running (for contact see my profile) 4th: if all fails, you could check with the developers of [eID applet](https://github.com/e-Contract/eid-applet), which was POIs base ... or give aspose a try ... which I wouldn't ;) – kiwiwings Oct 19 '21 at 18:44
  • For handling browser side (in case of web application), refer to answer: https://stackoverflow.com/a/55676351/9659885 On server side you may use any platform and pdf library of your choice. – Bharat Vasant Oct 20 '21 at 05:17

0 Answers0