I have to create an application which has XML data and creates Hash for signing and send the hash to an API to get the raw signature for XML and append signature for XML in Java How can I achieve this.
The same thing can be done in .Net by overriding SignedXml class like this
public class CustomSignedXml: SignedXml
{
public CustomSignedXml(XmlDocument xmlDoc) : base(xmlDoc)
{
}
public void ComputeSignature()
{
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
MethodInfo methodInfo = typeof(SignedXml).GetMethod("BuildDigestedReferences", BindingFlags.Instance | BindingFlags.NonPublic);
methodInfo.Invoke(this, null);
SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription;
if (signatureDescription == null)
throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated");
HashAlgorithm hashAlg = signatureDescription.CreateDigest();
if (hashAlg == null)
throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed");
MethodInfo methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic);
byte[] hashvalue = (byte[])methodInfo2.Invoke(this, new object[] { hashAlg });
var signature = GetSignatureFromServer(hashvalue);
m_signature.SignatureValue = signature;
}
}
And use CustomSignedXml class to sign using following meathod
public string GetSignedXml(string xmlDoc, X509Certificate2 PublicCertificate)
{
try
{
XmlDocument xmlDocumentToSign = new XmlDocument();
xmlDocumentToSign.LoadXml(xmlDoc);
CustomSignedXml signedXml = new CustomSignedXml(xmlDocumentToSign);
Reference reference = new Reference();
reference.Uri = "";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
signedXml.AddReference(reference);
signedXml.ComputeSignature();
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(GetKeyInfoData(PublicCertificate));
signedXml.KeyInfo = keyInfo;
var xmlDigitalSignature = signedXml.GetXml();
xmlDocumentToSign.DocumentElement.AppendChild(xmlDocumentToSign.ImportNode(xmlDigitalSignature, true));
return xmlDocumentToSign.OuterXml;
}
catch (Exception)
{
throw;
}
}
How can I do the same in JAVA