Sample code for 30+ languages & platforms
Swift

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let rsa = CkoRsa()!

    // Generate a 2048-bit RSA key.
    let privKey = CkoPrivateKey()!
    success = rsa.genKey(numBits: 2048, privKey: privKey)

    rsa.usePrivateKey(privKey: privKey)

    // Return the signature in hex.
    rsa.encodingMode = "hex"

    var strData: String? = "This is the string to be signed."

    // Sign the SHA256 hash of the string.
    var hexSig: String? = rsa.signStringENC(str: strData, hashAlg: "sha256")

    print("\(hexSig!)")

    // Now verify the signature:
    let pubKey = CkoPublicKey()!
    privKey.toPublicKey(pubKey: pubKey)
    rsa.usePublicKey(pubKey: pubKey)

    success = rsa.verifyStringENC(str: strData, hashAlg: "sha256", sig: hexSig)
    if success == true {
        print("Signature verified!")
    }
    else {
        print("\(rsa.lastErrorText!)")
    }

    // Try it with an invalid signature:
    success = rsa.verifyStringENC(str: strData, hashAlg: "sha256", sig: "not a valid sig")
    if success == true {
        print("Signature verified!")
    }
    else {
        print("Signature validation failed!")
    }

    // Try it with invalid data:
    success = rsa.verifyStringENC(str: "Not the original data", hashAlg: "sha256", sig: hexSig)
    if success == true {
        print("Signature verified!")
    }
    else {
        print("Signature validation failed!")
    }


}