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

RSA Encrypt and OpenSSL Decrypt

See more OpenSSL Examples

Demonstrates how to use Chilkat to RSA encrypt, and then use OpenSSL to decrypt.

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.

    let rsa = CkoRsa()!

    let privKey = CkoPrivateKey()!
    success = rsa.genKey(numBits: 2048, privKey: privKey)
    success = privKey.savePkcs8PemFile(path: "qa_output/privKey.pem")

    let pubKey = CkoPublicKey()!
    privKey.toPublicKey(pubKey: pubKey)

    rsa.encodingMode = "base64"
    var plainText: String? = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890"
    var bUsePrivateKey: Bool = false
    rsa.usePublicKey(pubKey: pubKey)
    var encryptedStr: String? = rsa.encryptStringENC(str: plainText, bUsePrivateKey: bUsePrivateKey)

    let bd = CkoBinData()!
    bd.appendEncoded(encData: encryptedStr, encoding: "base64")
    success = bd.writeFile(path: "qa_output/enc.dat")

    //  The OpenSSL command to decrypt is:
    //  openssl pkeyutl -in enc.dat -inkey privKey.pem -keyform PEM -pkeyopt rsa_padding_mode:pkcs1 -decrypt

    print("OK")

}