Sample code for 30+ languages & platforms
Java

Sign SOAP XML for New Zealand Customs Service

See more XAdES Examples

Demonstrates how to create an XAdES signed SOAP XML pertaining to the New Zealand Customs Service.

Note: This example requires Chilkat v9.5.0.96 or later.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
import com.chilkatsoft.chilkat2.XmlDSigGen;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        success = true;

        // Create the following XML to be signed:

        // <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        //     xmlns:v1="http://customs.govt.nz/jbms/msggate/reqresp/v1">
        //     <soapenv:Header>
        //         <wsse:Security soapenv:mustUnderstand="1"
        //             xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        //             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        //             <wsu:Timestamp wsu:Id="TS-037E78514E9B9132CB16817563559151">
        //                 <wsu:Created>2023-04-17T18:32:35.913Z</wsu:Created>
        //                 <wsu:Expires>2023-04-17T19:32:35.913Z</wsu:Expires>
        //             </wsu:Timestamp>
        //         </wsse:Security>
        //     </soapenv:Header>
        //     <soapenv:Body wsu:Id="id-8"
        //         xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        //         <v1:RequestResponse>
        //             <v1:Submitter>TEST1234</v1:Submitter>
        //             <v1:MailboxMsgId>999999</v1:MailboxMsgId>
        //         </v1:RequestResponse>
        //     </soapenv:Body>
        // </soapenv:Envelope>

        // Create a random ID like this: TS-037E78514E9B9132CB16817563559151
        StringBuilder tsId = new StringBuilder();
        tsId.append("TS-");
        tsId.appendRandom(16, "hex");

        // STR-037E78514E9B9132CB16817563559614
        StringBuilder strId = new StringBuilder();
        strId.append("STR-");
        strId.appendRandom(16, "hex");

        // KI-037E78514E9B9132CB16817563559583
        StringBuilder keyInfoId = new StringBuilder();
        keyInfoId.append("KI-");
        keyInfoId.appendRandom(16, "hex");

        // Create a date/time for the current time with this format:  2023-04-17T18:32:35.913Z
        DateTime dt = new DateTime();
        dt.setFromCurrentSystemTime();

        StringBuilder sbNow = new StringBuilder();
        sbNow.append(dt.getAsTimestamp(false));
        // If we really need the milliseconds, we can replace the "Z" with ".000Z"
        // The server will also likely accept a timestamp without milliseconds, such as 2023-04-17T18:32:35Z
        int n = sbNow.replace("Z", ".000Z");

        StringBuilder sbNowPlusOneHour = new StringBuilder();
        dt.addSeconds(3600);
        sbNowPlusOneHour.append(dt.getAsTimestamp(false));
        n = sbNowPlusOneHour.replace("Z", ".000Z");

        Xml xmlToSign = new Xml();
        xmlToSign.setTag("soapenv:Envelope");
        xmlToSign.addAttribute("xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
        xmlToSign.addAttribute("xmlns:v1", "http://customs.govt.nz/jbms/msggate/reqresp/v1");
        xmlToSign.updateAttrAt("soapenv:Header|wsse:Security", true, "soapenv:mustUnderstand", "1");
        xmlToSign.updateAttrAt("soapenv:Header|wsse:Security", true, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        xmlToSign.updateAttrAt("soapenv:Header|wsse:Security", true, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        xmlToSign.updateAttrAt("soapenv:Header|wsse:Security|wsu:Timestamp", true, "wsu:Id", tsId.getAsString());
        xmlToSign.updateChildContent("soapenv:Header|wsse:Security|wsu:Timestamp|wsu:Created", sbNow.getAsString());
        xmlToSign.updateChildContent("soapenv:Header|wsse:Security|wsu:Timestamp|wsu:Expires", sbNowPlusOneHour.getAsString());
        xmlToSign.updateAttrAt("soapenv:Body", true, "wsu:Id", "id-8");
        xmlToSign.updateAttrAt("soapenv:Body", true, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        xmlToSign.updateChildContent("soapenv:Body|v1:RequestResponse|v1:Submitter", "TEST1234");
        xmlToSign.updateChildContent("soapenv:Body|v1:RequestResponse|v1:MailboxMsgId", "999999");

        XmlDSigGen gen = new XmlDSigGen();

        gen.setSigLocation("soapenv:Envelope|soapenv:Header|wsse:Security");
        gen.setSigLocationMod(0);
        gen.setSigId("SIG-037E78514E9B9132CB16817563559695");
        gen.setSigNamespacePrefix("ds");
        gen.setSigNamespaceUri("http://www.w3.org/2000/09/xmldsig#");
        gen.setSignedInfoPrefixList("soapenv v1");
        gen.setIncNamespacePrefix("ec");
        gen.setIncNamespaceUri("http://www.w3.org/2001/10/xml-exc-c14n#");
        gen.setSignedInfoCanonAlg("EXCL_C14N");
        gen.setSignedInfoDigestMethod("sha256");

        // Set the KeyInfoId before adding references..
        gen.setKeyInfoId(keyInfoId.getAsString());

        // -------- Reference 1 --------
        Xml xml1 = new Xml();
        xml1.setTag("ds:Transforms");
        xml1.updateAttrAt("ds:Transform", true, "Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#");
        xml1.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "PrefixList", "wsse soapenv v1");
        xml1.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "xmlns:ec", "http://www.w3.org/2001/10/xml-exc-c14n#");

        gen.addSameDocRef2(tsId.getAsString(), "sha256", xml1, "");

        // -------- Reference 2 --------
        Xml xml2 = new Xml();
        xml2.setTag("ds:Transforms");
        xml2.updateAttrAt("ds:Transform", true, "Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#");
        xml2.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "PrefixList", "v1");
        xml2.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "xmlns:ec", "http://www.w3.org/2001/10/xml-exc-c14n#");

        gen.addSameDocRef2("id-8", "sha256", xml2, "");

        // Provide a certificate + private key. (PFX password is test123)
        Cert cert = new Cert();
        try {
            cert.loadPfxFile("qa_data/pfx/cert_test123.pfx", "test123");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        gen.setX509Cert(cert, true);

        gen.setKeyInfoType("Custom");

        // Create the custom KeyInfo XML..
        Xml xmlCustomKeyInfo = new Xml();
        xmlCustomKeyInfo.setTag("wsse:SecurityTokenReference");
        xmlCustomKeyInfo.addAttribute("wsu:Id", strId.getAsString());
        xmlCustomKeyInfo.updateAttrAt("wsse:KeyIdentifier", true, "EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
        xmlCustomKeyInfo.updateAttrAt("wsse:KeyIdentifier", true, "ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
        // Insert the single-line base64 of the signing certificate's DER
        cert.setUncommonOptions("Base64CertNoCRLF");
        xmlCustomKeyInfo.updateChildContent("wsse:KeyIdentifier", cert.getEncoded());

        xmlCustomKeyInfo.setEmitXmlDecl(false);
        gen.setCustomKeyInfoXml(xmlCustomKeyInfo.getXml());

        // Load XML to be signed...
        StringBuilder sbXml = new StringBuilder();
        xmlToSign.getXmlSb(sbXml);

        gen.setBehaviors("IndentedSignature");

        // Sign the XML...
        gen.setVerboseLogging(true);
        try {
            gen.createXmlDSigSb(sbXml);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Save the signed XML to a file.
        sbXml.writeFile("c:/temp/qa_output/signedXml.xml", "utf-8", false);

        System.out.println(sbXml.getAsString());
    }
}