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.