Sample code for 30+ languages & platforms
Swift

Sign a Byte Array to Create a Detached Signature in a Byte Array

See more Digital Signatures Examples

Signs data contained in a byte array to produce a detached signature (also in a byte array). Also shows how to verify the signature.

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.

    let cert = CkoCert()!
    success = cert.loadPfxFile(path: "qa_data/pfx/cert_test123.pfx", password: "test123")
    if success == false {
        print("\(cert.lastErrorText!)")
        return
    }

    let fac = CkoFileAccess()!

    var fileBytes: NSData
    fileBytes = fac.readEntireFile(path: "qa_data/pdf/sample.pdf")
    if fac.lastMethodSuccess != true {
        print("\(fac.lastErrorText!)")
        return
    }

    let crypt = CkoCrypt2()!

    success = crypt.setSigningCert(cert: cert)

    // We can sign any type of file.
    // The result is a detached signature (a signature that does not contain the data being signed).

    var sigBytes: NSData
    sigBytes = crypt.signBytes(bData: fileBytes)
    if crypt.lastMethodSuccess != true {
        print("\(crypt.lastErrorText!)")
        return
    }

    success = fac.writeEntireFile(path: "qa_output/sample.pdf.p7s", fileData: sigBytes)
    if fac.lastMethodSuccess != true {
        print("\(fac.lastErrorText!)")
        return
    }

    // We can verify the detached signature like this
    var verified: Bool = crypt.verifyBytes(bData1: fileBytes, sigData: sigBytes)
    if crypt.lastMethodSuccess != true {
        print("\(crypt.lastErrorText!)")
        return
    }

    print("Verified = \(verified)")

}