I have signed a XML document with java 8 without problems, until I upgrade to the Java 8u121 version, the code is:
String xml_entrada = "D:\\CeslySoft\\Ivap_facturador\\CPE\\FirmaXML\\Schema-20480510144-RC-20170327-0001.xml";
String xml_salida = "D:\\CeslySoft\\Ivap_facturador\\CPE\\FirmaXML\\20480510144-RC-20170327-0001.xml";
String certi_digital = "D:\\CeslySoft\\Ivap_facturador\\Certificados\\molchiclayo1.jks";
String clave = "9ghi0nmbR0ft";
String alias = "1";
String tipodoc = "09";
int indice = (tipodoc.equals("09")? 0: 1);
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1,null),
Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
null,null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(certi_digital), clave.toCharArray());
KeyStore.PrivateKeyEntry keyEntry
= (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(clave.toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Object> x509content = new ArrayList<>();
x509content.add(cert.getSubjectX500Principal().getName());
x509content.add(cert);
X509Data xd = kif.newX509Data(x509content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
//Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(xml_entrada));
InputSource is = new InputSource(new InputStreamReader(new FileInputStream(xml_entrada), "ISO-8859-1"));
Document doc = dbf.newDocumentBuilder().parse(is);
Node nodePadre = doc.getElementsByTagName("ext:ExtensionContent").item(indice);
nodePadre.getNodeValue();
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), nodePadre);
XMLSignature signature = fac.newXMLSignature(si, ki, null, "SignatureSP", null);
signature.sign(dsc);
OutputStream os = new FileOutputStream(xml_salida);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
trans.transform(new DOMSource(doc), new StreamResult(os));
The error is in the line of code:
signature.sign(dsc)
The error is:
javax.xml.crypto.XMLSignatureException: java.security.InvalidKeyException: Invalid RSA private key
......
With versions prior to Java 8u121, do not occur nothing errors.