Easy way to encrypt data in iOS

Today in high tech world data security is a very important parameter if your application is storing user and business information. When it comes to the mobile application it is not guaranteed the user will use the secure network channel to communicate to the remote server and if the user is using unsecured wireless network there are chances that the hacker can easily get the sensitive data from the application.

 

As we all know apple insists on security (learn more about mobile app security) and data privacy and it is best known for it. So we as developers should also give the same flavor to the user of our application and should always consider data security as one of the impotent pillars while writing the architecture of the application.

 

In Swift, there is a different easy way to achieve the data security either by using iOS keychain(with keychain wrapper), data protection(in capabilities ), third-party library, or built-in libraries.

 

iOS KeyChain

Keychain offers a secure alternative to store sensitive data other than UserDefault, plist or similar methods. One can easily save high sensitive data such as username, password,accessKey etc.

 

Storing small and simple bits of data such as API Key, UserId etc are simple and easy to store in UserDefault but it is no more secure. Hacker can easily read the values of the user-default from the device. Apple has provided keychain services API to deal with this security problem and help developers build apps that safely handle passwords and other sensitive information.

 

Keychain is quick and fast because data encryption automatically is taken care of before it is stored in the file system so there is no need to waste time building encryption algorithms. It can be configured to lock and when it is locked it is impossible to access and decrypt stored keychain items. In iOS, the keychain is locked when the device is locked and unlocked when the device is unlocked. Also even when it is unlocked, only apps that have created an item can access it, unless configured otherwise. You can also configure it to accessing keychains items across apps

 

Implement Keychain API directly for storing and retrieving data is the torturous job and it is time-consuming too.another option is to use wrapper class which is easy and fast there are many wrapper libraries are available on Github and cocoapods.com.

List of Good Wrapper class as follows.

 

1.swiftKeychainWrapper By Jason Rendel for swift

https://github.com/jrendel/SwiftKeychainWrapper.

2.Locksmith by Matthew Palmer for Swift

https://github.com/matthewpalmer/Locksmith.

3.Samkeychain by sam soffes for objective c

https://github.com/soffes/samkeychain.

A wrapper class gives top-level function such as add, edit and delete keychain item which is common to every wrapper class and each wrapper has its own slightly unique syntax and configurable options but they more or less follow the same pattern. Here I’m going to use swiftKeychainWrapper by Jason to demonstrate functionality

 

You can either install the swiftKeychainWrapper by pod or drag-drop the git project file into your project.

 

Assume that you have installed the pod/drag-drop the project below is the usage.

 

Adding item to the keychain.

 

let saveSuccessful: Bool = KeychainWrapper.standard.set(“Some String”, forKey: “myKey”)

Retrieve a string value from keychain:

let retrievedString: String? = KeychainWrapper.standard.string(forKey: “myKey”)

Remove a string value from keychain:

let removeSuccessful: Bool = KeychainWrapper.standard.removeObject(forKey: “myKey”)

 

 

import UIKit

import SwiftKeychainWrapper

 

class ViewController: UIViewController {

@IBOutlet weak var passwordtxt: UITextField!

override func viewDidLoad() {

super.viewDidLoad()

}

@IBAction func savePasswordBtnClicked(_ sender: Any) {

//

if let password = passwordtxt.text

{

let dataSaved:Bool = KeychainWrapper.standard.set(password , forKey: “userPassword”)

print(“password saved sucessfull:\(dataSaved)”)

}

}

@IBAction func retrievePasswordBtnClicked(_ sender: Any) {

let retrievedPassword: String? = KeychainWrapper.standard.string(forKey: “userPassword”)

print(“Saved Password \(retrievedPassword ?? “No Password saved”)”)

}

}

 

OutPut.

password saved sucessfull:true

Saved Password p@$$word

 

Removing an item from keychain.

let keyRemoved: Bool = KeychainWrapper.standard.remove(key: “userPassword“)

 

Data Protection:

There is another simple and easy way to enable the security layer on your app is by using the data protection feature in your project. It uses built-in hardware to store files in an encrypted format on disk and to decrypt them on demand.if data protection is enabled, protected files are inaccessible even to the app that created them if the device is locked by passcode or touch id.

 

How to enable Data Protection: Data protection can be enabled by turning on the data protection in Capability Tab of the project setting.

Now, if any of the files are created on the local device it is protected. The file can be created by Data and FileManager class.

 

Third party library:

RNCryptor and CryptoSwift are the two popular libraries available in ios for encryption data. It is easily available on GitHub.AES is an encryption technique commonly used. Best thing to use this library is it gets you up and running very quickly without having to worry about the underlying details the code is also open source so it is easy to analyze and audit it . We can also make changes as per any custom requirements into it. feature available in RNCryptor is AES-256 encryption, CBC mode, Password stretching with PBKDF2, Random IV, Encrypt then hash HMAC

 

Try This

OutPut

Read More
Jitendra Rai February 11, 2019 0 Comments

What needs to kept in mind for migrating from swift x.x to 4.2

Swift has covered a long journey from the date it was announced in WWDC till the last stable release in Oct 2018.during this phase there were many changes related to feature wise and also syntax-wise. Through version 3.0 the syntax of the swift went through significant evolution, with the core team making source stability a focus in later versions. In the first quarter of 2018 swift surpassed Objective -C in measured popularity.

 

Check the latest update in Swift 4

Swift 4.0 released in 2017, introduced several changes to some built-in classes and structures.also apple send out a notice to developers letting them know that starting in April of 2018, all new apps submitted to the App Store must be built using iOS 11 SDK which can be only done by Xcode 9 and later.

 

Migrating older codebase are  mandatory for support to iOS 11 SDK.I’m assuming that you have swift codebase in 2.xx and i will guide you the tips and tricks to migrate the whole code base to the latest swift.let’s start with the upgrading to new swift 4.

 

Note : If your code base is in swift 2.x and you wanted to upgrade to latest swift then it is better to first migrate it to swift 3 by using Xcode 8.xx and then go for swift 4.xx to avoid complications

 

How to reach 2.x to 3.x?

First download Xcode 8.x.Xcode 8 comes with a Swift Migrator tool that helps you migrate your project to swift 3.x and also update it new SDKs.When you open your project with Xcode 8.x for the first time you will be prompt with the inbuild migration assistant to do a migration process. In case if you miss the prompt the assistant can also be invoked manually from the Xcode menu Edit | Convert |To Current Swift Syntax Now just choose the version and the target to migrate.

Now click next it will bring up the Generate Preview sheet and the assistant will initiate a migration to get source changes. when this is done, now you will be presented with all the changes that will be applied once you click ‘Save’.

 

Once the conversion is done Xcode show’s the original code and the converted code , the original source is on the right and the changes done by the tool are on the left.Y ou can still make the changes to the left side if you feel like. Now save the changes Xcode will save that changes to the original file. After doing this just clean the project and build it. All the error are not fixed by the migrator tool some error is to be done by the manual process, now we are good to go phase 2.

 

3.x to 4.x  

Once you have done with the migration to swift 3.x now open the same project in the latest Xcode. Here again, we have to open the migration tool and follow the same process as we have to do in process one of migrating the code.

 

Required Changes After Migration Tool.

 

There are some changes which are to be done manually after the migration tool has done with the changes. Here are a few of the most common changes that we had to make.

Closure parameter labels – Swift 3 removed support for argument labels in function types this requires to removing parameter labels from closures. Here we simply remove the argument labels in the closures.  

Optional protocol functions

Signatures for UIKit protocol delegate methods have changed for many classes UITableViewController and UICollectionViewController.

For Example:

Func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) has changed to : func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath).

 

Private Changed to File Private

 

Private declarations are now changes to file-private which is the new keyword that behaves exactly as private for restricting access to the current file. The new file-private allows access only within the current declaration, restricting access even further than before.

 

Multiple unwrapping conditions

 

To add Multiple conditions in conditional unwrapping we can trim down the ‘let’ keyword but now it is required.

 

//This will not work with swift 3.0

If let x = getSetX(),y = getSetY() {

…..

….

}   

//Swift 3.0

 

If let x = getSetX(),let y = getSetY() {

…..

….

}

 

Conditions no longer contain where

Before we can use where clause with the conditions making our if let statement more readable but swift 3.0 where is removed.  

 

// Not work with swift 3.0

If let x = getSetX(), where x== true {

…..

….

}

 

//Work with swift 3.0

If let x = getSetX(), x== true {

…..

….

}

 

Vast Renaming

There are vast changes in the class, methods name but you do not have to worry about it will be done automatically by the migration tool, here are the some of the common ones that you’ll likely to run into.

 

The NS prefix has been removed from the vast majority of APIs and many singleton-like patterns are no longer methods but properties. Also, sharedManager or sharedApplication is now just shared.

 

NSNotificationCenter,defaultCenter() is now NotificationCenter.default with additional renaming such as postNotificationName -> post

 

Names for notifications are no longer strings but enums of the type Notification.Name

 

NSBundle.mainBundle().pathForResource is now Bundle.main.path

 

.respondsToSelector() is now .responds(to:#selector())

 

componentsSeparatedByString(“.”) is now components(separatedBy:”.”)

 

NSUserDefaults.standardUserDefaults() is now userDefaults.standard with additional renaming such as objectForKey() -> object(forKey:)

 

NSProcessInfo.processInfo is now ProcessInfo.processInfo

 

enumerate() on arrays and dictionaries is now enumerated()

 

NSFileManager.defaultManager() is now FileManager.default

 

NSDate is now just Date

 

NSDateFormatter is now just DateFormatter

 

NSUTF8StringEncoding is now much more reasonably named with String.Encoding.utf8

 

Dispatch_queue_create and similar have been drastically simplified to names such as DispatchQueue.

These are just some of the big items you’ll run into when looking at your Migration tools Diff.

Read More
Jitendra Rai February 7, 2019 0 Comments

What’s new in swift 4.2

Swift 4.2.1 is finally released !.New Xcode 10.1 comes with the latest swift 4.2.1 and with the bundle of the feature with it. Swift latest release will really provide the great features which will definitely save the developer’s time and complexity in coding. Swift 4.2.1 release majorly targets for code optimization and run time performance.

Boolean Toggling

Now it is easy to toggle the boolean value just by calling the function.toggle() function can be used to change the boolean state of the variable from true to false and vice versa.

Try this:

 

var userPromoCode = false

userPromoCode.toggle()

 

Here after the execution of the code the value of userPromoCode will be True.toggle() function help in means of readability and easiness if your write complex data structure.

 

Random Method

 

For randomizing the number we use C API method arc4random_uniform(10) till now,  which is included in foundation library.Now swift has its own function to do this random() function can be used to generate a range of the random number on whatever numeric type you like. Randomization is not limit to numeric type collection can also be use it .shuffle() and shuffled() are two  methods can be used for collections to shuffle the content of the collection safely.

 

Try this:

 

let  random_Num     = Int.random(in:0 ..< 10)

let  random_Float    = Float.random(in:0..< 10)

 

For Collections.

 

var diceRoll = [1,2,3,4,5,6]

diceRoll.shuffle()

print(“Dice Rolled \(diceRoll)”)

 

let itemShuffled = diceRoll.shuffled()      //Returns shuffled array

print(“Dice Rolled \()”)

 

Sequence Methods

Any one with Java back ground will love this new sequence method in swift .Sequence Methods are used for find the element,Index of match element and direct index of the elements.

last(where:) , lastIndex(where:) , lastIndex(of:) are the methods introduced in swift out which two requires a closure as an argument and last requires the elements to be searched.

 

Try this.

 

1.let numberArr = [30,50,60,10,5,12,46,67]

print(“Last Highest Number \(numberArr.last(where:{$0 > 50}))”)

// Prints 67

$0 is the first value compare with the other elements

 

print(“Last Highest Number \(numberArr.lastIndex(where:{$0 > 50}))”)

// Prints 7

 

print(“Last Highest Number \(numberArr.astIndex(of:60))”)

// Prints 2

 

Sequence method not yet done we have allSatisfy(_:) that validate every element and return true  if all match a given condition.

 

let numArr = [30,50,60,10,4,12,46,68]

let isEvenArr = numArr.allSatisfy({$0 % 2 == 0 })

// isEvenArr hold True value.

 

removeAll(where:) method remove all items in collection which matches the condition.

 

Try this

 

Let empName = [“sam”,”Rocky”,”Smith”,”logan”]

empName.removeAll{$0.hasSuffix(“ky”)}

print(empName)

//Prints sam,logan,smith

 

Dynamic Member Lookup

Dynamic member lookup allows swift to call a subscript method when accessing properties. It is the easiest way of accessing property just by using dot operator . Once  you register your class/struct with @dynamicMemberLookup  keyword the compiler doesn’t complain with what so ever name you call the subscript method and at the same time it is type safe.

 

Let try this in playground.

 

@dynamicMemberLookup

struct Person

{

   subscript(dynamicMember name:String) -> Int

   {

       return name.count

   }

}

let personObj = Person()

personObj.pqwrs

//Prints

5

So it’s No matter what’s the name of the property it call the subscript method name

 

// 1

@dynamicMemberLookup

class Employee {

 let name: String

 let age: Int

 private let empPersonal: [String: String]

 

 init(name: String, age: Int, details: [String: String]) {

   self.name = name

   self.age = age

   self.details = details

 }

 

 // 2

 subscript(dynamicMember key: String) -> String {

   switch key {

     case “info”:

       return “\(name) is \(age) years old.”

     default:

       return details[key] ?? “”

   }

 }

}

 

// Creating Object of the Class

 

let details = [“department”: “IT”, “location”: “Mumbai”]

let me = Employee(name: “Logan”, age: 32, details: details)

me.info   // “Logan is 32 years old.”

me.department  // “IT”

Read More
Jitendra Rai February 7, 2019 0 Comments
WhatsApp chat