Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Validate Certificate using OCSP Protocol

See more Certificates Examples

Demonstrates how to validate a certificate (check the revoked status) using the OCSP protocol.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    //  This example will check the revoked status of a certificate loaded from a file.
    let cert = CkoCert()!
    success = cert.load(fromFile: "qa_data/certs/google.crt")
    if success == false {
        print("\(cert.lastErrorText!)")
        return
    }

    //  Get the cert's OCSP URL.
    var ocspUrl: String? = cert.ocspUrl

    //  Build the JSON that will be the OCSP request.

    //  Possible hash algorithms are sha1, sha256, sha384, sha512.  
    var hashAlg: String? = "sha256"
    let prng = CkoPrng()!
    let json = CkoJsonObject()!
    json.emitCompact = false
    //  Read more about OCSP nonce lengths
    json.updateString(jsonPath: "extensions.ocspNonce", value: prng.genRandom(numBytes: 16, encoding: "base64"))
    json.i = 0
    json.updateString(jsonPath: "request[i].cert.hashAlg", value: hashAlg)
    json.updateString(jsonPath: "request[i].cert.issuerNameHash", value: cert.hash(of: "IssuerDN", hashAlg: hashAlg, encoding: "base64"))
    json.updateString(jsonPath: "request[i].cert.issuerKeyHash", value: cert.hash(of: "IssuerPublicKey", hashAlg: hashAlg, encoding: "base64"))
    json.updateString(jsonPath: "request[i].cert.serialNumber", value: cert.serialNumber)

    print("\(json.emit()!)")

    //  Our OCSP request looks something like this:
    //  {
    //    "extensions": {
    //      "ocspNonce": "qZDfbpO+nUxRzz6c/SPjE5QCAsPfpkQlRDxTnGl0gnxt7iXO"
    //    },
    //    "request": [
    //      {
    //        "cert": {
    //          "hashAlg": "sha1",
    //          "issuerNameHash": "9u2wY2IygZo19o11oJ0CShGqbK0=",
    //          "issuerKeyHash": "d8K4UJpndnaxLcKG0IOgfqZ+uks=",
    //          "serialNumber": "6175535D87BF94B6"
    //        }
    //      }
    //    ]
    //  }

    let ocspRequest = CkoBinData()!
    let http = CkoHttp()!

    //  Convert our JSON to a binary (ASN.1) OCSP request
    success = http.createOcspRequest(requestDetails: json, ocspRequest: ocspRequest)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    //  Send the OCSP request to the OCSP server
    let resp = CkoHttpResponse()!
    success = http.httpBd(verb: "POST", url: ocspUrl, bd: ocspRequest, contentType: "application/ocsp-request", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    //  Get the binary (ASN.1) OCSP reply
    let ocspReply = CkoBinData()!
    resp.getBodyBd(binData: ocspReply)

    //  Convert the binary reply to JSON.
    //  Also returns the overall OCSP response status.
    let jsonReply = CkoJsonObject()!
    var ocspStatus: Int = http.parseOcspReply(ocspReply: ocspReply, replyData: jsonReply).intValue

    //  The ocspStatus can have one of these values:
    //  -1:  The ARG1 does not contain a valid OCSP reply.
    //  0:  Successful - Response has valid confirmations..
    //  1: Malformed request - Illegal confirmation request.
    //  2: Internal error - Internal error in issuer.
    //  3: Try later -  Try again later.
    //  4: Not used - This value is never returned.
    //  5: Sig required - Must sign the request.
    //  6: Unauthorized - Request unauthorized.

    if ocspStatus < 0 {
        print("Invalid OCSP reply.")
        return
    }

    print("Overall OCSP Response Status: \(ocspStatus)")

    //  Let's examine the OCSP response (in JSON).
    jsonReply.emitCompact = false
    print("\(jsonReply.emit()!)")

    //  The JSON reply looks like this:
    //  (Use the online tool at https://tools.chilkat.io/jsonParse.cshtml
    //  to generate JSON parsing code.)

    //  {
    //    "responseStatus": 0,
    //    "responseTypeOid": "1.3.6.1.5.5.7.48.1.1",
    //    "responseTypeName": "ocspBasic",
    //    "response": {
    //      "responderIdChoice": "KeyHash",
    //      "responderKeyHash": "d8K4UJpndnaxLcKG0IOgfqZ+uks=",
    //      "dateTime": "20180803193937Z",
    //      "cert": [
    //        {
    //          "hashOid": "1.3.14.3.2.26",
    //          "hashAlg": "SHA-1",
    //          "issuerNameHash": "9u2wY2IygZo19o11oJ0CShGqbK0=",
    //          "issuerKeyHash": "d8K4UJpndnaxLcKG0IOgfqZ+uks=",
    //          "serialNumber": "6175535D87BF94B6",
    //          "status": 0,
    //          "thisUpdate": "20180803193937Z",
    //          "nextUpdate": "20180810193937Z"
    //        }
    //      ]
    //    }
    //  }
    //  

    //  The certificate status:
    var certStatus: Int = -1
    if jsonReply.hasMember(jsonPath: "response.cert[0].status") == true {
        certStatus = jsonReply.int(of: "response.cert[0].status").intValue
    }

    //  Possible certStatus values are:
    //  -1: No status returned.
    //  0: Good
    //  1: Revoked
    //  2: Unknown.
    print("Certificate Status: \(certStatus)")

}