I have written the following .NET Framework 3.5 C# method which takes the location of an XML document and an object representation of an X509 digital certificate (with a private key) and returns the XML document as an object with the XML Signature (XMLDsig) embedded as first child element of the root.
The thing is that I direly need to be able to do the exact same procedure with Java SE 6, but I have not written any Java in ages and have no clue where to begin.
Can anyone provide the equivalent method in Java code that produces the exact same XML output?
private static XmlDocument SignXmlDocument(string xmlFilePath, X509Certificate2 certificate)
{
// load xml from disk preserving whitespaces
XmlDocument xmlDocument = new XmlDocument { PreserveWhitespace = true };
xmlDocument.Load(xmlFilePath);
// create signed xml with a same-document reference containing an enveloped-signature transform
SignedXml signedXml = new SignedXml(xmlDocument) { SigningKey = certificate.PrivateKey };
Reference reference = new Reference { Uri = "" };
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
// embed public key information for signature validation purposes
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
keyInfo.AddClause(keyInfoX509Data);
signedXml.KeyInfo = keyInfo;
// compute and retreive the signature xml
signedXml.ComputeSignature();
XmlElement xmldsigXmlElement = signedXml.GetXml();
// insert the signature xml into the xml document as first child of the root element
xmlDocument.DocumentElement.PrependChild(xmlDocument.ImportNode(xmldsigXmlElement, true));
return xmlDocument;
}
The following does the same thing in Java. It requires a PKCS12 certificate file on disk.
Check out the Java XML Digital Signature API: https://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html