Sample code for 30+ languages & platforms
Swift

XAdES using TSA Requiring Client Certificate

See more XML Digital Signatures Examples

Demonstrates how to create an XMLDSig (XAdES) signed document which includes an EncapsulatedTimestamp using a TSA (TimeStamp Authority) server requiring client certificate authentication. One such TSA is https://www3.postsignum.cz/TSS/TSS_crt/

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    success = true

    // Load the XML to be signed.  For example, the XML to be signed might contain something like this:

    // <?xml version="1.0" encoding="utf-8"?>
    // <TransakcniLogSystemu xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://nsess.public.cz/erms_trans/v_01_01" Id="Signature1">
    //   <TransLogInfo>
    //     <Identifikator>XYZ ABC</Identifikator>
    //     <DatumVzniku>2022-12-20T14:39:02.3625922+01:00</DatumVzniku>
    //     <DatumCasOd>2022-12-20T14:26:26.88</DatumCasOd>
    //     <DatumCasDo>2022-12-20T14:39:02.287</DatumCasDo>
    //     <Software>XYZ</Software>
    //     <VerzeSoftware>2.0.19.32</VerzeSoftware>
    //   </TransLogInfo>
    //   <Udalosti>
    //     <Udalost>
    //       <Poradi>1</Poradi>
    // ...

    // Load the XML to be signed from a file.
    // (XML can be loaded from other source, such as a string variable.)
    let sbXml = CkoStringBuilder()!
    success = sbXml.loadFile(path: "xmlToSign.xml", charset: "utf-8")

    let gen = CkoXmlDSigGen()!

    gen.sigLocation = "TransakcniLogSystemu"
    gen.sigLocationMod = 0
    gen.sigId = "SignatureID-Signature1"
    gen.sigNamespacePrefix = "ds"
    gen.sigNamespaceUri = "http://www.w3.org/2000/09/xmldsig#"
    gen.signedInfoCanonAlg = "C14N"
    gen.signedInfoDigestMethod = "sha256"

    // Set the KeyInfoId before adding references..
    gen.keyInfoId = "KeyInfoId-Signature-Signature1"

    // Create an Object to be added to the Signature.

    // Note: Chilkat will automatically fill in the values marked as "TO BE GENERATED BY CHILKAT" at the time of signing.
    // The EncapsulatedTimestamp will be automatically generated.

    let object1 = CkoXml()!
    object1.tag = "xades:QualifyingProperties"
    object1.addAttribute(name: "xmlns:xades", value: "http://uri.etsi.org/01903/v1.3.2#")
    object1.addAttribute(name: "Target", value: "#Signature1")

    object1.updateAttrAt(tagPath: "xades:SignedProperties", autoCreate: true, attrName: "Id", attrValue: "SignedProperties-Signature-Signature1")
    object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningTime", value: "TO BE GENERATED BY CHILKAT")
    object1.updateAttrAt(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:CertDigest|ds:DigestMethod", autoCreate: true, attrName: "Algorithm", attrValue: "http://www.w3.org/2001/04/xmlenc#sha256")
    object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:CertDigest|ds:DigestValue", value: "TO BE GENERATED BY CHILKAT")
    object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:IssuerSerialV2", value: "TO BE GENERATED BY CHILKAT")

    // The EncapsulatedTimestamp will be included in the unsigned properties.
    object1.updateAttrAt(tagPath: "xades:UnsignedProperties|xades:UnsignedSignatureProperties|xades:SignatureTimeStamp", autoCreate: true, attrName: "Id", attrValue: "signature-timestamp-5561-8212-3316-5191")
    object1.updateAttrAt(tagPath: "xades:UnsignedProperties|xades:UnsignedSignatureProperties|xades:SignatureTimeStamp|ds:CanonicalizationMethod", autoCreate: true, attrName: "Algorithm", attrValue: "http://www.w3.org/2001/10/xml-exc-c14n#")
    object1.updateAttrAt(tagPath: "xades:UnsignedProperties|xades:UnsignedSignatureProperties|xades:SignatureTimeStamp|xades:EncapsulatedTimeStamp", autoCreate: true, attrName: "Encoding", attrValue: "http://uri.etsi.org/01903/v1.2.2#DER")
    object1.updateChildContent(tagPath: "xades:UnsignedProperties|xades:UnsignedSignatureProperties|xades:SignatureTimeStamp|xades:EncapsulatedTimeStamp", value: "TO BE GENERATED BY CHILKAT")

    gen.add(id: "XadesObjectId-Signature1", content: object1.getXml(), mimeType: "", encoding: "")

    // -------- Reference 1 --------
    gen.addObjectRef(id: "SignedProperties-Signature-Signature1", digestMethod: "sha256", canonMethod: "EXCL_C14N", prefixList: "", refType: "http://uri.etsi.org/01903#SignedProperties")

    // -------- Reference 2 --------
    gen.addSameDocRef(id: "KeyInfoId-Signature-Signature1", digestMethod: "sha256", canonMethod: "EXCL_C14N", prefixList: "", refType: "")
    gen.setRefIdAttr(uri_or_id: "KeyInfoId-Signature-Signature1", value: "ReferenceKeyInfo")

    // -------- Reference 3 --------
    gen.addSameDocRef(id: "", digestMethod: "sha256", canonMethod: "EXCL_C14N", prefixList: "", refType: "")
    gen.setRefIdAttr(uri_or_id: "", value: "Reference-Signature1")

    // Provide a certificate + private key. (PFX password is test123)
    let cert = CkoCert()!
    success = cert.loadPfxFile(path: "qa_data/pfx/cert_test123.pfx", password: "test123")
    if success != true {
        print("\(cert.lastErrorText!)")
        return
    }

    gen.setX509Cert(cert: cert, usePrivateKey: true)

    gen.keyInfoType = "X509Data"
    gen.x509Type = "Certificate"

    gen.behaviors = "IndentedSignature"

    // -------------------------------------------------------------------------------------------
    // To have the EncapsulatedTimeStamp automatically added... 
    // 1) Add the <xades:EncapsulatedTimeStamp Encoding="http://uri.etsi.org/01903/v1.2.2#DER">TO BE GENERATED BY CHILKAT</xades:EncapsulatedTimeStamp>
    //    to the unsigned properties.  (This was accomplished in the above code.)
    // 2) Specify the TSA URL (Timestamping Authority URL).
    //    Here we specify the TSA URL:
    // -------------------------------------------------------------------------------------------

    let jsonTsa = CkoJsonObject()!
    jsonTsa.updateString(jsonPath: "timestampToken.tsaUrl", value: "https://www3.postsignum.cz/TSS/TSS_crt/")
    jsonTsa.updateBool(jsonPath: "timestampToken.requestTsaCert", value: true)
    gen.setTsa(json: jsonTsa)

    // -------------------------------------------------------------------------------------------
    // In this case, the TSA requires client certificate authentication.
    // To provide your client certificate, the application will instantiate a Chilkat HTTP object,
    // then set it up with a SSL/TLS client certificate, and then tell the XmlDSigGen object
    // to use the HTTP object for connections to the TSA server.
    // -------------------------------------------------------------------------------------------
    let http = CkoHttp()!
    success = http.setSslClientCertPfx(pfxPath: "/home/bob/pfxFiles/myClientSideCertWithPrivateKey.pfx", pfxPassword: "pfxPassword")
    if success != true {
        print("\(http.lastErrorText!)")
        return
    }

    // Tell the XmlDSigGen object to use the above HTTP object for TSA communications.
    gen.setHttpObj(http: http)

    // Sign the XML...
    success = gen.createXmlDSigSb(sbXml: sbXml)
    if success != true {
        print("\(gen.lastErrorText!)")
        return
    }

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

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

    print("\(sbXml.getAsString()!)")

}