Sample code for 30+ languages & platforms
Java

XML-DSig Add Reference with Transforms Specified Explicitly

Demonstrates how to use the new AddSameDocRef2 method to explicitly specify the XML Transforms fragment.

Chilkat Java Downloads

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

public class ChilkatExample {

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

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

        success = true;

        // Create the following XML to be signed:

        // <doc>
        //     <s id="s1">Some text...</s>
        //     <p>Some text...</p>
        //     <p class="note">A note...</p>
        // </doc>

        // Use this online tool to generate code from sample XML:
        // Generate Code to Create XML

        Xml xmlToSign = new Xml();
        xmlToSign.setTag("doc");
        xmlToSign.updateAttrAt("s", true, "id", "s1");
        xmlToSign.updateChildContent("s", "Some text...");
        xmlToSign.updateChildContent("p", "Some text...");
        xmlToSign.updateAttrAt("p[1]", true, "class", "note");
        xmlToSign.updateChildContent("p[1]", "A note...");

        System.out.println(xmlToSign.getXml());

        XmlDSigGen gen = new XmlDSigGen();

        gen.setSigLocation("doc");
        gen.setSigLocationMod(0);
        gen.setSigId("Signature-78f29839-06af-448f-b479-ca46457fab1b-Signature");
        gen.setSigNamespacePrefix("ds");
        gen.setSigNamespaceUri("http://www.w3.org/2000/09/xmldsig#");
        gen.setSigValueId("Signature-78f29839-06af-448f-b479-ca46457fab1b-SignatureValue");
        gen.setSignedInfoCanonAlg("C14N");
        gen.setSignedInfoDigestMethod("sha1");

        // Set the KeyInfoId before adding references..
        gen.setKeyInfoId("Signature-78f29839-06af-448f-b479-ca46457fab1b-KeyInfo");

        // The following XML to be added as an Object to the Signature

        // Use this online tool to generate code from sample XML:
        // Generate Code to Create XML

        // <xades:QualifyingProperties Id="Signature-78f29839-06af-448f-b479-ca46457fab1b-QualifyingProperties" Target="#Signature-78f29839-06af-448f-b479-ca46457fab1b-Signature" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#">
        //     <xades:SignedProperties Id="Signature-78f29839-06af-448f-b479-ca46457fab1b-SignedProperties">
        //         <xades:SignedSignatureProperties>
        //             <xades:SigningTime>TO BE GENERATED BY CHILKAT</xades:SigningTime>
        //             <xades:SigningCertificate>
        //                 <xades:Cert>
        //                     <xades:CertDigest>
        //                         <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
        //                         <ds:DigestValue>TO BE GENERATED BY CHILKAT</ds:DigestValue>
        //                     </xades:CertDigest>
        //                     <xades:IssuerSerial>
        //                         <ds:X509IssuerName>TO BE GENERATED BY CHILKAT</ds:X509IssuerName>
        //                         <ds:X509SerialNumber>TO BE GENERATED BY CHILKAT</ds:X509SerialNumber>
        //                     </xades:IssuerSerial>
        //                 </xades:Cert>
        //             </xades:SigningCertificate>
        //         </xades:SignedSignatureProperties>
        //         <xades:SignedDataObjectProperties>
        //             <xades:DataObjectFormat ObjectReference="#Reference-24eb6003-d41c-442c-a731-d4c58f94790b">
        //                 <xades:Description/>
        //                 <xades:ObjectIdentifier>
        //                     <xades:Identifier Qualifier="OIDAsURN">urn:oid:1.2.840.10003.5.109.10</xades:Identifier>
        //                     <xades:Description/>
        //                 </xades:ObjectIdentifier>
        //                 <xades:MimeType>text/xml</xades:MimeType>
        //                 <xades:Encoding/>
        //             </xades:DataObjectFormat>
        //         </xades:SignedDataObjectProperties>
        //     </xades:SignedProperties>
        // </xades:QualifyingProperties>

        Xml object1 = new Xml();
        object1.setTag("xades:QualifyingProperties");
        object1.addAttribute("Id", "Signature-78f29839-06af-448f-b479-ca46457fab1b-QualifyingProperties");
        object1.addAttribute("Target", "#Signature-78f29839-06af-448f-b479-ca46457fab1b-Signature");
        object1.addAttribute("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
        object1.addAttribute("xmlns:xades", "http://uri.etsi.org/01903/v1.3.2#");
        object1.updateAttrAt("xades:SignedProperties", true, "Id", "Signature-78f29839-06af-448f-b479-ca46457fab1b-SignedProperties");
        object1.updateChildContent("xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningTime", "TO BE GENERATED BY CHILKAT");
        // Note: It may be that http://www.w3.org/2001/04/xmlenc#sha256 is needed in the following line instead of http://www.w3.org/2000/09/xmldsig#sha1
        object1.updateAttrAt("xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:CertDigest|ds:DigestMethod", true, "Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
        object1.updateChildContent("xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:CertDigest|ds:DigestValue", "TO BE GENERATED BY CHILKAT");
        object1.updateChildContent("xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:IssuerSerialV2", "TO BE GENERATED BY CHILKAT");
        object1.updateAttrAt("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat", true, "ObjectReference", "#Reference-24eb6003-d41c-442c-a731-d4c58f94790b");
        object1.updateChildContent("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:Description", "");
        object1.updateAttrAt("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Identifier", true, "Qualifier", "OIDAsURN");
        object1.updateChildContent("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Identifier", "urn:oid:1.2.840.10003.5.109.10");
        object1.updateChildContent("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Description", "");
        object1.updateChildContent("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:MimeType", "text/xml");
        object1.updateChildContent("xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:Encoding", "");

        System.out.println(object1.getXml());

        gen.addObject("", object1.getXml(), "", "");

        // -------- Reference 1 --------

        // Create the following Transforms fragment:

        // Use this online tool to generate code from sample XML:
        // Generate Code to Create XML

        // <ds:Transforms>
        //     <ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
        //     <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
        //     <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
        //         <ds:XPath xmlns:ds="http://www.w3.org/2000/09/xmldsig#">not(ancestor-or-self::ds:Signature)</ds:XPath>
        //     </ds:Transform>
        // </ds:Transforms>

        Xml xml1 = new Xml();
        xml1.setTag("ds:Transforms");
        xml1.updateAttrAt("ds:Transform", true, "Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
        xml1.updateAttrAt("ds:Transform[1]", true, "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature");
        xml1.updateAttrAt("ds:Transform[2]", true, "Algorithm", "http://www.w3.org/TR/1999/REC-xpath-19991116");
        xml1.updateAttrAt("ds:Transform[2]|ds:XPath", true, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
        xml1.updateChildContent("ds:Transform[2]|ds:XPath", "not(ancestor-or-self::ds:Signature)");

        // This is the "Transforms" XML fragment passed to AddSameDocRef2.
        System.out.println(xml1.getXml());

        gen.addSameDocRef2("", "sha1", xml1, "");

        gen.setRefIdAttr("", "Reference-24eb6003-d41c-442c-a731-d4c58f94790b");

        // -------- Reference 2 --------
        gen.addObjectRef("Signature-78f29839-06af-448f-b479-ca46457fab1b-SignedProperties", "sha1", "", "", "http://uri.etsi.org/01903#SignedProperties");

        // -------- Reference 3 --------
        gen.addSameDocRef("Signature-78f29839-06af-448f-b479-ca46457fab1b-KeyInfo", "sha1", "", "", "");

        // 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("X509Data+KeyValue");
        gen.setX509Type("CertChain");

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

        gen.setBehaviors("IndentedSignature");

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

        // -----------------------------------------------

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

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

        // ----------------------------------------
        // Verify the signatures we just produced...
        XmlDSig verifier = new XmlDSig();
        try {
            verifier.loadSignatureSb(sbXml);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int numSigs = verifier.getNumSignatures();
        int verifyIdx = 0;
        while (verifyIdx < numSigs) {
            verifier.setSelector(verifyIdx);
            try {
                verifier.verifySignature(true);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            verifyIdx = verifyIdx + 1;
        }

        System.out.println("All signatures were successfully verified.");
    }
}