Tuesday, January 26, 2016

Encrypt/decrypt a string with code-generated RSA public/private keys in Swift

The example below shows how to:

- generate private and public RSA keys in Swift.
- encrypt and decrypt a string in Swift.

The Xcode used with this example is version 7.2 (Swift 2.1.1).

1. Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Generation of RSA private and public keys
        let parameters: [String: AnyObject] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeySizeInBits as String: 1024
        ]
        
        var publicKey, privateKey: SecKey?

        SecKeyGeneratePair(parameters, &publicKey, &privateKey)
        
        //Encrypt a string with the public key
        let message = "This is my message."
        let blockSize = SecKeyGetBlockSize(publicKey!)
        var messageEncrypted = [UInt8](count: blockSize, repeatedValue: 0)
        var messageEncryptedSize = blockSize

        var status: OSStatus!
        
        status = SecKeyEncrypt(publicKey!, SecPadding.PKCS1, message, message.characters.count, &messageEncrypted, &messageEncryptedSize)
        
        if status != noErr {
            print("Encryption Error!")
            return
        }
        
        //Decrypt the entrypted string with the private key
        var messageDecrypted = [UInt8](count: blockSize, repeatedValue: 0)
        var messageDecryptedSize = messageEncryptedSize
        
        status = SecKeyDecrypt(privateKey!, SecPadding.PKCS1, &messageEncrypted, messageEncryptedSize, &messageDecrypted, &messageDecryptedSize)
        
        if status != noErr {
            print("Decryption Error!")
            return
        }
        
        print(NSString(bytes: &messageDecrypted, length: messageDecryptedSize, encoding: NSUTF8StringEncoding)!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

2. Result:

This is my message.

References:
Apple's document: Certificate, Key, and Trust Services Reference
SecKeyGeneratePair in Swift
Encrypt/decrypt a string with public/private keys imported from PEM files (Swift)

Study Raspberry Pi blog:
Encrypt/decrypt a string with RSA public/private keys in PHP
Encrypt/decrypt a string with RSA public/private PEM files using Python
Encrypt/decrypt a string with code-generated RSA public/private keys in Python
Sending an RSA encrypted message from client to Python socket server

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)

5 comments:

  1. how to use my own public key please reply as soon u can

    ReplyDelete
  2. after encryption ,i want to conver this
    messageEncrypted to base64 .
    please help me to do.
    am new to ios devolopment.

    ReplyDelete
    Replies
    1. You may convert messageEncrypted ([UInt8] array) to NSData and then encode the NSData to base64. See part 2 of Convert NSData/[UInt8] to Base64 in Swift

      Delete
  3. Hello,
    I have some troubles when converting the messageEncrypted. The message is always different every time i run the code.
    I need the same message to send to the server.
    Do you have any solution?

    Thanks in advance

    ReplyDelete