Sample code for 30+ languages & platforms
Swift

Azure Key Vault Sign with a Certificate's Private Key

See more Azure Key Vault Examples

Signs a hash using the private key of a certificate previously imported to an Azure Key Vault.

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.

    // See Azure Key Vault Get Certificates for a more detailed explanation
    // for how Chilkat is automatically getting the OAuth2 access token for your application.

    // Provide information needed for Chilkat to automatically get an OAuth2 access token as needed.
    let json = CkoJsonObject()!
    json.updateString(jsonPath: "client_id", value: "APP_ID")
    json.updateString(jsonPath: "client_secret", value: "APP_PASSWORD")
    json.updateString(jsonPath: "resource", value: "https://vault.azure.net")
    json.updateString(jsonPath: "token_endpoint", value: "https://login.microsoftonline.com/TENANT_ID/oauth2/token")

    // In this example, we'll sign the SHA256 hash of the string "This is a test"
    let sb = CkoStringBuilder()!
    var signedString: String? = "This is a test"
    sb.append(value: signedString)
    var hash_base64url: String? = sb.getHash(algorithm: "sha256", encoding: "base64url", charset: "utf-8")

    // We're going to send a POST to the following URL:
    // POST {vaultBaseUrl}/keys/{key-or-cert-name}/{key-or-cert-version}/sign?api-version=7.4

    // For example:

    // POST https://VAULT_NAME.vault.azure.net/keys/CERT_NAME/CERT_VERSION/sign?api-version=7.4
    // 
    // {
    //   "alg": "RS512",
    //   "value": "RUE3Nzg4NTQ4QjQ5RjFFN0U2NzAyQzhDNEMwMkJDOTA1MTYyOTUzNjI5NDhBNzZDQTlFOTM1NDA2M0ZGMjk2Mg"
    // }

    // The alg can be one of the following
    // ES256  ECDSA using P-256 and SHA-256
    // ES256K ECDSA using P-256K and SHA-256
    // ES384  ECDSA using P-384 and SHA-384
    // ES512  ECDSA using P-521 and SHA-512
    // PS256  RSASSA-PSS using SHA-256 and MGF1 with SHA-256
    // PS384  RSASSA-PSS using SHA-384 and MGF1 with SHA-384
    // PS512  RSASSA-PSS using SHA-512 and MGF1 with SHA-512
    // RS256  RSASSA-PKCS1-v1_5 using SHA-256
    // RS384  RSASSA-PKCS1-v1_5 using SHA-384
    // RS512  RSASSA-PKCS1-v1_5 using SHA-512

    // The sample POST above uses SHA512.  We'll instead sign a SHA256 hash..

    let jsonBody = CkoJsonObject()!
    jsonBody.updateString(jsonPath: "alg", value: "RS256")
    jsonBody.updateString(jsonPath: "value", value: hash_base64url)

    let http = CkoHttp()!

    // Instead of providing an actual access token, we give Chilkat the information that allows it to 
    // automatically fetch the access token using the OAuth2 client credentials flow.
    http.authToken = json.emit()

    http.setUrlVar(name: "certName", value: "importCert01")
    http.setUrlVar(name: "certVersion", value: "7140c8755ed14839b5d86a9f7e7f0497")
    // Note: Replace "VAULT_NAME" with the name of your Azure key vault.
    var url: String? = "https://VAULT_NAME.vault.azure.net/keys/{$certName}/{$certVersion}/sign?api-version=7.4"
    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: url, json: jsonBody, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    var statusCode: Int = resp.statusCode.intValue

    let jsonResp = CkoJsonObject()!
    resp.getBodyJson(json: jsonResp)

    jsonResp.emitCompact = false
    print("\(jsonResp.emit()!)")

    if statusCode != 200 {
        print("Failed.")
        return
    }

    // A successful response body contains JSON like this:
    // Note: Azure's documentation is not very clear, but base64url is the encoding, not "base64".
    // {
    //   "kid": "https://kvchilkat.vault.azure.net/keys/importCert01/7140c8755ed14839b5d86a9f7e7f0497",
    //   "value": "JzWd2YF21gjtW ... Em37hKOQ"
    // }

    // Let's validate the signature using the cert's public key.
    // This example will load the corresponding certificate from a local file and will verify the signature against the original data.
    // 
    let cert = CkoCert()!
    success = cert.load(fromFile: "qa_data/certs/chilkat_code_signing_2024.cer")
    if success == false {
        print("\(cert.lastErrorText!)")
        return
    }

    let rsa = CkoRsa()!
    // Tell the RSA object to use the cert's public key.
    success = rsa.setX509Cert(cert: cert, usePrivateKey: false)
    if success == false {
        print("\(rsa.lastErrorText!)")
        return
    }

    // Verify the signature using the cert's public key against the original string.
    rsa.encodingMode = "base64url"
    var valid: Bool = rsa.verifyStringENC(str: signedString, hashAlg: "sha-256", sig: jsonResp.string(of: "value"))
    print("signature valid = \(valid)")

}