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)

Tuesday, January 19, 2016

UIPasteboard - Copy text to clipboard / pasteboard

This post shows an example app with a button and a text view. By pressing the button, a string is copied to the clipboard/pasteboard. Then the string may be pasted into the text view by tapping and holding.

Modify ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Button
        let button : UIButton!
        button = UIButton(frame: CGRectMake(0, 0, 300, 30))
        button.center = CGPointMake(view.center.x, 100)
        button.setTitle("Copy String", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
        //TextField
        let textView = UITextView(frame: CGRectMake(0, 0, 200, 100))
        textView.center = CGPointMake(view.center.x, 200)
        textView.backgroundColor = UIColor.cyanColor()
        textView.textColor = UIColor.blackColor()
        textView.textAlignment = NSTextAlignment.Center
        view.addSubview(textView)
    }
    
    func btnPressed(sender: UIButton) {
        
        //Copy a string to the pasteboard.
        UIPasteboard.generalPasteboard().string = "The quick brown fox jumps over the lazy dog."
        
        //Alert
        let alertController = UIAlertController(title: "", message: "String copied to pasteboard!", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }

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

}

Result:


Sunday, January 17, 2016

Apple TV (4th generation) unboxing and writing the first tvOS Hello World app

Apple TV (4th generation) unboxing

Let's start unboxing the Apple TV!!



Apple TV, remote, power cord and lightning cable.


Connectors for power, HDMI, USB-C, and RJ-45 ethernet.


Comparison: Apple TV (3rd generation) vs Apple TV (4th generation)

Comparison: Apple TV (3rd generation) vs Apple TV (4th generation)

Comparison: Remote (3rd generation) vs Remote (4th generation)

Comparison: Remote (3rd generation) vs Remote (4th generation)

The first thing to do after connecting the Apple TV to power and the TV set, is to pair the remote by clicking the trackpad of the remote.

Press the area on top of the menu and home buttons of the remote.

Select the language and country.

Configure Wi-Fi settings.

The interface for setting up the Wi-Fi password manually is difficult with the remote.
So I set up Wi-Fi password with an iPhone.

The initial screen of Apple TV.

To control the Apple TV using an iPhone / iPad, the software of Apple TV must be updated:

Settings -> System -> Software Updates -> Update Software

Download the latest Remote app to your iPhone or iPad. The app not only works as a remote controller, but also helps to enter the searching keywords a keyboard. 

Let's go through different functions of the Apple TV.

Movies may be purchased.


Best apps of 2015.

Each country has different app categories.


While an app is selected, click the get button with the downward arrow to download.


Games may also be downloaded.

Art Channel is a good app.

Masterpiece slideshow on your TV screen with Art Channel!!

Beautiful screensaver

Now it's time to write the first Hello World app. You'll need a Mac and the Xcode development tool.

This tutorial shows how to develop the first simple app on Apple TV:
Develop the first tvOS app (Hello World) for the new Apple TV (4th generation)

The app displayed with the tvOS simulator should be like this:


Then a USB-A male to USB-C male cable is required for downloading the app from Mac to Apple TV. The cable should be with reasonable length, otherwise the Mac has to be placed closely to the TV. My cable is 3-meter long and it seems to be shorter than I thought.

Connect the USB-C connector of the USB cable to Apple TV. Connect the other side of the USB cable to a Mac.

Build and run the tvOS Swift project on the Mac, and the app is shown on the TV screen:


Press the Menu or Home button of the remote, the TVHelloWorld app with an empty icon is shown:



References:
Develop the first tvOS app (Hello World) for the new Apple TV (4th generation)
Everything You Need to Know About the New Apple TV App Store
By December 9, 2015:
2624 apps on Apple TV App Store.
38% of apps are games.

Develop the first tvOS app (Hello World) for the new Apple TV (4th generation)

This tutorial is for both iOS developers and inexperienced programmers.

The greatest feature of the new Apple TV (4th generation) is the support for the App Store. Unlike previous Apple TVs, apps now can be downloaded and installed on these boxes. This feature gives software developers great opportunities to implement custom apps for TVs. Since the tvOS operating system of Apple TV is based on iOS, developing Apple apps should not be a big problem for iPhone developers.

The step-by-step instructions below will explain how to build the first Hello World app in Swift for Apple TV. The software development tool used in this example is Xcode 7.2 installed on Mac OS X El Capitan 10.11.2.

Hello World app on Apple TV Simulator

Requirement:
In this section, all you need is a Mac. The simulator can be run on a Mac without the Apple TV box.

1. Go to the Member Center of the Apple Developer website and create a free Apple Developer account. (You need an Apple ID first.) You don't need to pay US$99 annual fee until you are about to submit your app to the Apple TV App Store.

2. Install the latest OS X operating system and the Xcode integrated development environment (IDE) on a Mac.




3. The toolbar with a lot of application icons at the bottom of the screen is called the Dock. The two application icons at the left of the Dock are Finder and Launchpad. Select Finder -> Applications -> Xcode or click Launchpad and then select Xcode on the desktop.



4. Select Create a new Xcode project.

5. Select tvOS -> Application -> Single View Application.

6. Enter your Product Name, Organization Name, and Organization Identifier. The Organization Identifier should be in the format of com.organizationname. The product name used here is TVHelloWorld.
Select Next.

Select the directory you want to save the project and select Create.

7. Search for images with "tvos jpg" on web and save one of the files as tvos.jpg to the desktop. Drag the file from Finder to the Project navigator of Xcode.


Select Copy items if needed and Finish.

Now tvos.jpg has been copied into the Project navigator:

8. Select ViewController.swift in the Project navigator. Edit the file as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Set the background color
        view.backgroundColor = UIColor.orangeColor()
        
        let gap : CGFloat = 300
        
        let label = UILabel(frame: CGRectMake(0,0,1000,200))
        label.center = CGPoint(x: view.center.x, y: gap)
        label.text = "Hello World!\nMy first app with tvOS!" // "\n" is new line character
        label.font = UIFont(name: (label.font?.fontName)!, size: 50)
        label.numberOfLines = 0 //Multi-lines
        label.textAlignment = NSTextAlignment.Center //Align to center
        view.addSubview(label)
        
        let imageView = UIImageView(frame: CGRectMake(0, 0, 500, 500))
        imageView.center = CGPoint(x: view.center.x, y: view.frame.height-gap)
        imageView.image = UIImage(named: "tvos.jpg")
        imageView.contentMode = UIViewContentMode.ScaleAspectFit //Keep the aspect ratio
        view.addSubview(imageView)
    }

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

}

The result should be similar to this:


9. Make sure that Apple TV 1080p (tvOS Simulator) is selected.


Click the Build and Run button.

10. The Apple TV simulator should be turned on after a while. The window size of the simulator may be changed under Window -> Scale.



The tvOS simulator window should be like this:


If it is not displayed, click the Stop button in Xcode:
And then click the Build and Run button in Xcode again.


11. To go back to the home screen, select Hardware -> Home.

The other method to go back to the home screen is to enable the keyboard for the simulator. Select Hardware -> Keyboard -> Connect Hardware Keyboard. Then hit the Esc key.

The tvOS simulator should go back to the home mode like this:

Use the left and right keys to switch between apps. Unlike in iOS simulator, selection by mouse does not work in Apple TV simulator.

Press the return/enter key to enter the app.

Now you have completed the first section - Hello World app on Apple TV Simulator.

Here is the second section:

Install app on Apple TV

Requirements:
1. The second section of this tutorial needs a physical Apple TV (4th generation).  You may choose between 32GB (US$149) and 64GB (US$199) models.

2. You also need a USB-A male to USB-C male cable for downloading your app from Mac to Apple TV. The cable should be with reasonable length, otherwise your Mac has to be placed closely to the TV. My cable is 3-meter long and it seems to be shorter than I thought.

2. Connect the USB cable to the Apple TV and Mac.

3. Select Apple TV as device in Xcode. Click the Build and Run button.

4. If the Failed to code sign message appears, select Fix issue.

5. Then... the Hello World app is showing on TV!!


6. Press the MENU button of the remote, an empty icon with the app name is shown on the TV screen.



Reference:
Apple TV (4th generation) unboxing and writing the first tvOS Hello World app
Apple TV Tech Talks Videos