Swift
Swift
Signed Zip as Base64 with XAdES-BES
See more XAdES Examples
This example is to help companies implement a solution for sending XAdES-BES to the Polish government for reporting purposes. Specifically:Przed podpisaniem deklaracja zbiorcza (PIT-11Z, PIT-8CZ, PIT-40Z, PIT-RZ) musi zostać
umieszczona w archiwum ZIP. W tym przypadku, podpisywany jest plik archiwum ZIP,
przyjmujący w podpisie XAdES-BES formę zakodowaną base64.
The example demonstrates the following:
- Zip an XML file (PIT-11Z.xml is zipped to PIT-11Z.zip)
- Create XML to be signed, where the XML contains the base64 encoded content of the PIT-11Z.zip archive.
- XAdES-BES sign the XML containing the base64 zip.
This example will also show the reverse:
- Verify the signed XML.
- Extract the PIT-11z.zip from the signed XML.
- Unzip the PIT-11Z.zip to get the original PIT-11Z.xml
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Zip the PIT-11Z.xml to create PIT-11Z.zip (not as a .zip file, but in-memory).
let sbXmlToZip = CkoStringBuilder()!
success = sbXmlToZip.loadFile(path: "qa_data/xml/PIT-11Z.xml", charset: "utf-8")
if success != true {
print("Failed to load the XML to be zipped.")
return
}
let zip = CkoZip()!
// Initialize the zip object. No file is created in this call.
// It should always return true.
success = zip.newZip(zipPath: "PIT-11Z.zip")
// Add the XML to be zipped.
zip.addSb(pathInZip: "PIT-11Z.xml", sb: sbXmlToZip, charset: "utf-8")
// Write the zip to a BinData object.
let bdZip = CkoBinData()!
zip.writeBd(binData: bdZip)
// The contents of the bdZip will be retrieved in base64 format when needed below..
let gen = CkoXmlDSigGen()!
gen.sigLocation = ""
gen.sigLocationMod = 0
gen.sigId = "Signature_2a8df7f8-b958-40cc-83f6-edb53b837347_19"
gen.sigNamespacePrefix = "ds"
gen.sigNamespaceUri = "http://www.w3.org/2000/09/xmldsig#"
gen.sigValueId = "SignatureValue_2a8df7f8-b958-40cc-83f6-edb53b837347_52"
gen.signedInfoId = "SignedInfo_2a8df7f8-b958-40cc-83f6-edb53b837347_41"
gen.signedInfoCanonAlg = "C14N"
gen.signedInfoDigestMethod = "sha1"
// Set the KeyInfoId before adding references..
gen.keyInfoId = "KeyInfo_2a8df7f8-b958-40cc-83f6-edb53b837347_24"
// Create an Object to be added to the Signature.
let object1 = CkoXml()!
object1.tag = "xades:QualifyingProperties"
object1.addAttribute(name: "xmlns:xades", value: "http://uri.etsi.org/01903/v1.3.2#")
object1.addAttribute(name: "Id", value: "QualifyingProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_43")
object1.addAttribute(name: "Target", value: "#Signature_2a8df7f8-b958-40cc-83f6-edb53b837347_19")
object1.updateAttrAt(tagPath: "xades:SignedProperties", autoCreate: true, attrName: "Id", attrValue: "SignedProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_4e")
object1.updateAttrAt(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties", autoCreate: true, attrName: "Id", attrValue: "SignedSignatureProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_0a")
// Chilkat will replace the strings "TO BE GENERATED BY CHILKAT" with actual values when the signature is created.
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningTime", value: "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(tagPath: "xades:SignedProperties|xades:SignedSignatureProperties|xades:SigningCertificateV2|xades:Cert|xades:CertDigest|ds:DigestMethod", autoCreate: true, attrName: "Algorithm", attrValue: "http://www.w3.org/2000/09/xmldsig#sha1")
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")
object1.updateAttrAt(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties", autoCreate: true, attrName: "Id", attrValue: "SignedDataObjectProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_4b")
object1.updateAttrAt(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat", autoCreate: true, attrName: "ObjectReference", attrValue: "#Reference1_2a8df7f8-b958-40cc-83f6-edb53b837347_27")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:Description", value: "MIME-Version: 1.0\r\nContent-Type: application/zip\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: filename="PIT-11Z.zip"")
object1.updateAttrAt(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Identifier", autoCreate: true, attrName: "Qualifier", attrValue: "OIDAsURI")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Identifier", value: "http://www.certum.pl/OIDAsURI/signedFile/1.2.616.1.113527.3.1.1.3.1")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:Description", value: "Opis formatu dokumentu oraz jego pelna nazwa")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:ObjectIdentifier|xades:DocumentationReferences|xades:DocumentationReference", value: "http://www.certum.pl/OIDAsURI/signedFile.pdf")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:DataObjectFormat|xades:MimeType", value: "application/zip")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:CommitmentTypeIndication|xades:CommitmentTypeId|xades:Identifier", value: "http://uri.etsi.org/01903/v1.2.2#ProofOfApproval")
object1.updateChildContent(tagPath: "xades:SignedProperties|xades:SignedDataObjectProperties|xades:CommitmentTypeIndication|xades:AllSignedDataObjects", value: "")
object1.updateAttrAt(tagPath: "xades:UnsignedProperties", autoCreate: true, attrName: "Id", attrValue: "UnsignedProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_55")
// Emit XML in compact (single-line) format to avoid whitespace problems.
object1.emitCompact = true
gen.add(id: "", content: object1.getXml(), mimeType: "", encoding: "")
// Create an Object to be added to the Signature.
// This is where we add the base64 representation of the PIT-11Z.zip
gen.add(id: "Object1_2a8df7f8-b958-40cc-83f6-edb53b837347", content: bdZip.getEncoded(encoding: "base64"), mimeType: "", encoding: "http://www.w3.org/2000/09/xmldsig#base64")
// -------- Reference 1 --------
gen.addObjectRef(id: "Object1_2a8df7f8-b958-40cc-83f6-edb53b837347", digestMethod: "sha1", canonMethod: "C14N_WithComments", prefixList: "", refType: "")
gen.setRefIdAttr(uri_or_id: "Object1_2a8df7f8-b958-40cc-83f6-edb53b837347", value: "Reference1_2a8df7f8-b958-40cc-83f6-edb53b837347_27")
// -------- Reference 2 --------
gen.addObjectRef(id: "SignedProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_4e", digestMethod: "sha1", canonMethod: "", prefixList: "", refType: "http://uri.etsi.org/01903#SignedProperties")
gen.setRefIdAttr(uri_or_id: "SignedProperties_2a8df7f8-b958-40cc-83f6-edb53b837347_4e", value: "SignedProperties-Reference_2a8df7f8-b958-40cc-83f6-edb53b837347_28")
// 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 == false {
print("\(cert.lastErrorText!)")
return
}
gen.setX509Cert(cert: cert, usePrivateKey: true)
gen.keyInfoType = "X509Data"
gen.x509Type = "Certificate"
// This will be an enveloping signature where the Signature element
// is the XML document root, the signed data is contained within Object
// tag(s) within the Signature.
// Therefore, pass an empty sbXml to CreateXmlDsigSb.
let sbXml = CkoStringBuilder()!
// The Polish government's XmlDSig implementation requires that we reproduce an attribute-sorting error.
// (This is an error in the XML canonicalization that is not noticed when both the signature-creation code and signature-verification code use
// the same XML canonicalization implementation w/ the bug.)
gen.behaviors = "AttributeSortingBug,CompactSignedXml"
// Sign the XML...
success = gen.createXmlDSigSb(sbXml: sbXml)
if success == false {
print("\(gen.lastErrorText!)")
return
}
// -----------------------------------------------
// Save the signed XML to a file.
success = sbXml.writeFile(path: "qa_output/signedXml.xml", charset: "utf-8", emitBom: false)
print("\(sbXml.getAsString()!)")
// ----------------------------------------
// Verify the signature we just produced...
let verifier = CkoXmlDSig()!
success = verifier.loadSignatureSb(sbXmlSig: sbXml)
if success == false {
print("\(verifier.lastErrorText!)")
return
}
var verified: Bool = verifier.verifySignature(verifyReferenceDigests: true)
if verified != true {
print("\(verifier.lastErrorText!)")
return
}
print("This signature was successfully verified.")
// ------------------------------------
// Finally, let's extract the .zip from the signed XML, and then unzip the original PIT-11Z.xml from the in-memory zip.
let xml = CkoXml()!
xml.loadSb(sb: sbXml, autoTrim: true)
// The base64 image of the PIT-11Z.zip is in the 2nd ds:Object child of the ds:Signature (the ds:Signature is the root element of the signed XML).
// (ds:Object[0] would be the 1st ds:Object child. Index 1 is the 2nd ds:Object child.)
var strZipBase64: String? = xml.getChildContent(tagPath: "ds:Object[1]")
bdZip.clear()
bdZip.appendEncoded(encData: strZipBase64, encoding: "base64")
if bdZip.numBytes.intValue == 0 {
print("Something went wrong.. we dont' have any data..")
return
}
success = zip.openBd(binData: bdZip)
if success == false {
print("\(zip.lastErrorText!)")
return
}
// Get the 1st file in the zip, which should be the PIT-11Z.xml
let entry = CkoZipEntry()!
success = zip.entry(at: 0, entry: entry)
if success == false {
print("Zip contains no files...")
return
}
// Get the XML:
var origXml: String? = entry.unzip(toString: 0, srcCharset: "utf-8")
print("Original XML extracted from base64 zip:")
print("\(origXml!)")
}