Skip to content

Instantly share code, notes, and snippets.

@hkneptune
Created October 9, 2023 03:51
Show Gist options
  • Save hkneptune/2284d2288126920c980888048bc30d0d to your computer and use it in GitHub Desktop.
Save hkneptune/2284d2288126920c980888048bc30d0d to your computer and use it in GitHub Desktop.
Signing XML File Content with p12 File
public static String signXmlContent(String inputFile, String keyStoreFilePath,
String keyStorePassword, String keyStoreAlias) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(keyStoreFilePath), keyStorePassword.toCharArray());
DocumentBuilderFactory buildFactory = DocumentBuilderFactory.newInstance();
buildFactory.setNamespaceAware(true);
Document document = buildFactory.newDocumentBuilder().parse(inputFile);
XMLSignatureFactory xmLSignatureFactory = XMLSignatureFactory.getInstance("DOM",
(Provider) Class.forName("org.jcp.xml.dsig.internal.dom.XMLDSigRI").newInstance());
KeyInfoFactory keyInfoFactory = xmLSignatureFactory.getKeyInfoFactory();
XMLSignature signature = xmLSignatureFactory.newXMLSignature(xmLSignatureFactory.newSignedInfo(
xmLSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null),
xmLSignatureFactory.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
null), Collections.singletonList(xmLSignatureFactory.newReference("",
xmLSignatureFactory.newDigestMethod(DigestMethod.SHA256, null),
Collections.singletonList(xmLSignatureFactory.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null))), keyInfoFactory.newKeyInfo(
new ArrayList<>(Collections.singletonList(keyInfoFactory.newX509Data(
new ArrayList<>(Collections.singletonList(keyStore.getCertificate(keyStoreAlias))))))));
signature.sign(
new DOMSignContext(keyStore.getKey(keyStoreAlias, keyStorePassword.toCharArray()),
document.getDocumentElement()));
StringWriter stringWriter = new StringWriter();
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(document.getDocumentElement()), new StreamResult(stringWriter));
String result = stringWriter.toString().replaceAll("&#13;", "");
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment