KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
// Step 7: Create an XMLSignature object. In JSR-105, the XMLSignature
// interface models the Signature element of the W3C recommendation.
XMLSignature signature = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);
// Step 8: Instantiate a DOMSignContext object, and register the private
// key with it. The XMLSignContext interface (which DOMSignContext
// implements) contains context information for generating XML
// signatures.
Document doc = dbf.newDocumentBuilder().newDocument();
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc);
// Step 9: Sign. The sign() operation in the XMLSignature interface
// signs the XMLSignature. Under the surface, the method carries out
// several actions, including computing the digest values for all the
// References based on the corresponding digest methods, and calculating
// the signature value based on the signature method and the private
// key. The signature value is captured by the embedded SignatureValue
// class in the XMLSignature instance, and calling getSignatureValue()
// of the XMLSignature instance will return the SignatureValue object
// populated with the resulting value.
signature.sign(dsc);
// Final step : Save XML Signature to a XML file
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(XML_SOURCE_SIGNED)));