Browse Source

Keychain access options

Evgenii Neumerzhitckii 10 years ago
parent
commit
a22d10897b

+ 2 - 1
README.md

@@ -1,6 +1,7 @@
 # iOS/Swift helper functions for storing text in Keychain
 
-This is a collection of helper functions for writing/reading text from a Keychain. As you probably noticed Apple's keychain API is a bit verbose. This class was designed to provide shorter syntax for accomplishing a simple task: reading/writing text values for specified keys. Tested in iOS 7 and 8.
+This is a collection of helper functions for saving text and data in the Keychain.
+ As you probably noticed Apple's keychain API is a bit verbose. This class was designed to provide shorter syntax for accomplishing a simple task: reading/writing text values for specified keys. Tested in iOS 7 and 8.
 
 ## What's Keychain?
 

+ 4 - 4
keychain.xcodeproj/project.pbxproj

@@ -16,7 +16,7 @@
 		2BCB00A81A83354D0022C93A /* keychainTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BCB00A71A83354D0022C93A /* keychainTests.swift */; };
 		2BCB00B21A8335740022C93A /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 2BCB00B11A8335740022C93A /* Default-568h@2x.png */; };
 		2BCB00B51A8335AF0022C93A /* TegKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BCB00B41A8335AF0022C93A /* TegKeychain.swift */; };
-		7E49F5341B1BDDCE00FBC3FF /* TegKeychainOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E49F5331B1BDDCE00FBC3FF /* TegKeychainOptions.swift */; };
+		7E49F5361B1BE41B00FBC3FF /* TegKeychainAccessOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E49F5351B1BE41B00FBC3FF /* TegKeychainAccessOptions.swift */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXContainerItemProxy section */
@@ -43,7 +43,7 @@
 		2BCB00A71A83354D0022C93A /* keychainTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = keychainTests.swift; sourceTree = "<group>"; };
 		2BCB00B11A8335740022C93A /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
 		2BCB00B41A8335AF0022C93A /* TegKeychain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TegKeychain.swift; sourceTree = "<group>"; };
-		7E49F5331B1BDDCE00FBC3FF /* TegKeychainOptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TegKeychainOptions.swift; sourceTree = "<group>"; };
+		7E49F5351B1BE41B00FBC3FF /* TegKeychainAccessOptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TegKeychainAccessOptions.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
@@ -126,8 +126,8 @@
 			isa = PBXGroup;
 			children = (
 				2BCB00B41A8335AF0022C93A /* TegKeychain.swift */,
+				7E49F5351B1BE41B00FBC3FF /* TegKeychainAccessOptions.swift */,
 				2B48E3391A92F47800456D2F /* TegKeychainConstants.swift */,
-				7E49F5331B1BDDCE00FBC3FF /* TegKeychainOptions.swift */,
 			);
 			name = Lib;
 			sourceTree = "<group>";
@@ -233,9 +233,9 @@
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				7E49F5341B1BDDCE00FBC3FF /* TegKeychainOptions.swift in Sources */,
 				2BCB00941A83354D0022C93A /* ViewController.swift in Sources */,
 				2BCB00921A83354D0022C93A /* AppDelegate.swift in Sources */,
+				7E49F5361B1BE41B00FBC3FF /* TegKeychainAccessOptions.swift in Sources */,
 				2B48E33A1A92F47800456D2F /* TegKeychainConstants.swift in Sources */,
 				2BCB00B51A8335AF0022C93A /* TegKeychain.swift in Sources */,
 			);

+ 68 - 3
keychain/TegKeychain.swift

@@ -1,9 +1,26 @@
 import UIKit
 import Security
 
+
+/**
+
+A collection of helper functions for saving text and data in the keychain.
+
+*/
 public class TegKeychain {
   
-  public class func set(key: String, value: String) -> Bool {
+  /**
+  
+  Store text value in the keychain item.
+  
+  :param: key Key under which the text value is stored in the keychain.
+  :param: value Text string to be written to the keychain.
+  :param: withAccess Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
+
+  */
+  public class func set(key: String, value: String,
+    withAccess access: TegKeychainAccessOptions? = nil) -> Bool {
+    
     if let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
       return set(key, value: data)
     }
@@ -11,11 +28,28 @@ public class TegKeychain {
     return false
   }
 
-  public class func set(key: String, value: NSData) -> Bool {
+  /**
+  
+  Store data in the keychain item.
+  
+  :param: key Key under which the data is stored in the keychain.
+  :param: value Data to be written to the keychain.
+  :param: withAccess Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
+  
+  :returns: True if the text was successfully written to the keychain.
+  
+  */
+  public class func set(key: String, value: NSData,
+    withAccess access: TegKeychainAccessOptions? = nil) -> Bool {
+
+    let accessible = access?.value ?? TegKeychainAccessOptions.defaultOption.value
+      
     let query = [
       TegKeychainConstants.klass       : TegKeychainConstants.classGenericPassword,
       TegKeychainConstants.attrAccount : key,
-      TegKeychainConstants.valueData   : value ]
+      TegKeychainConstants.valueData   : value,
+      TegKeychainConstants.accessible  : accessible
+    ]
     
     SecItemDelete(query as CFDictionaryRef)
     
@@ -24,6 +58,14 @@ public class TegKeychain {
     return status == noErr
   }
 
+  /**
+  
+  Retrieves the text value from the keychain.
+  
+  :param: key The key that is used to read the keychain item.
+  :returns: The text value from the keychain. Returns nil if unable to read the item.
+  
+  */
   public class func get(key: String) -> String? {
     if let data = getData(key),
       let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
@@ -34,6 +76,14 @@ public class TegKeychain {
     return nil
   }
 
+  /**
+  
+  Retrieves the data from the keychain.
+  
+  :param: key The key that is used to read the keychain item.
+  :returns: The text value from the keychain. Returns nil if unable to read the item.
+  
+  */
   public class func getData(key: String) -> NSData? {
     let query = [
       TegKeychainConstants.klass       : kSecClassGenericPassword,
@@ -52,6 +102,14 @@ public class TegKeychain {
     return nil
   }
 
+  /**
+  
+  Deletes the keychain item.
+  
+  :param: key The key that is used to delete the keychain item.
+  :returns: True if the item was successfully deleted.
+  
+  */
   public class func delete(key: String) -> Bool {
     let query = [
       TegKeychainConstants.klass       : kSecClassGenericPassword,
@@ -62,6 +120,13 @@ public class TegKeychain {
     return status == noErr
   }
 
+  /**
+  
+  Deletes all keychain items used by the app.
+  
+  :returns: True if the keychain items were successfully deleted.
+  
+  */
   public class func clear() -> Bool {
     let query = [ kSecClass as String : kSecClassGenericPassword ]
     

+ 107 - 0
keychain/TegKeychainAccessOptions.swift

@@ -0,0 +1,107 @@
+import Security
+
+/**
+
+These constants are use to determining when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
+
+*/
+public enum TegKeychainAccessOptions {
+  
+  /**
+  
+  The data in the keychain item can be accessed only while the device is unlocked by the user.
+  
+  This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
+  
+  This is the default value for keychain items added without explicitly setting an accessibility constant.
+  
+  */
+  case AccessibleWhenUnlocked
+  
+  /**
+  
+  The data in the keychain item can be accessed only while the device is unlocked by the user.
+  
+  This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
+  
+  */
+  case AccessibleWhenUnlockedThisDeviceOnly
+  
+  /**
+  
+  The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
+  
+  After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
+  
+  */
+  case AccessibleAfterFirstUnlock
+  
+  /**
+  
+  The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
+  
+  After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
+  
+  */
+  case AccessibleAfterFirstUnlockThisDeviceOnly
+  
+  /**
+  
+  The data in the keychain item can always be accessed regardless of whether the device is locked.
+  
+  This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
+  
+  */
+  case AccessibleAlways
+  
+  /**
+  
+  The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
+  
+  This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
+  
+  */
+  case AccessibleWhenPasscodeSetThisDeviceOnly
+  
+  /**
+  
+  The data in the keychain item can always be accessed regardless of whether the device is locked.
+  
+  This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
+  
+  */
+  case AccessibleAlwaysThisDeviceOnly
+  
+  static var defaultOption: TegKeychainAccessOptions {
+    return .AccessibleWhenUnlocked
+  }
+  
+  var value: String {
+    switch self {
+    case .AccessibleWhenUnlocked:
+      return toString(kSecAttrAccessibleWhenUnlocked)
+      
+    case .AccessibleWhenUnlockedThisDeviceOnly:
+      return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
+      
+    case .AccessibleAfterFirstUnlock:
+      return toString(kSecAttrAccessibleAfterFirstUnlock)
+      
+    case .AccessibleAfterFirstUnlockThisDeviceOnly:
+      return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
+      
+    case .AccessibleAlways:
+      return toString(kSecAttrAccessibleAlways)
+      
+    case .AccessibleWhenPasscodeSetThisDeviceOnly:
+      return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
+      
+    case .AccessibleAlwaysThisDeviceOnly:
+      return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
+    }
+  }
+  
+  func toString(value: CFStringRef) -> String {
+    return TegKeychainConstants.toString(value)
+  }
+}

+ 3 - 122
keychain/TegKeychainConstants.swift

@@ -8,134 +8,15 @@ public struct TegKeychainConstants {
   public static var valueData: String { return toString(kSecValueData) }
   public static var returnData: String { return toString(kSecReturnData) }
   public static var matchLimit: String { return toString(kSecMatchLimit) }
-  
-  
-  /**
-  
-  A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see TegKeychainAccessibilityConstants.
-  
-  */
-  public static var accessible: String { return toString(kSecAttrAccessible) }
-
-  private static func toString(value: CFStringRef) -> String {
-    return (value as? String) ?? ""
-  }
-}
-
-
-/**
-
-These constants are values for TegKeychainConstants.accessible used for determining when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
-
-*/
-struct TegKeychainAccessibilityConstants {
-  
-
-  
-
-  
-  
-}
 
-
-/**
-
-These constants are values for TegKeychainConstants.accessible used for determining when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
-
-*/
-public enum TegKeychainAccessibilityOptions {
-  
   /**
   
-  The data in the keychain item can be accessed only while the device is unlocked by the user.
-  
-  This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
-  
-  This is the default value for keychain items added without explicitly setting an accessibility constant.
-  
-  */
-  case AccessibleWhenUnlocked
-  
-  /**
-  
-  The data in the keychain item can be accessed only while the device is unlocked by the user.
-  
-  This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
+  A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see TegKeychainAccessOptions.
   
   */
-  case AccessibleWhenUnlockedThisDeviceOnly
-  
-  /**
-  
-  The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
-  
-  After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
-  
-  */
-  case AccessibleAfterFirstUnlock
+  public static var accessible: String { return toString(kSecAttrAccessible) }
 
-  /**
-  
-  The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
-  
-  After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
-  
-  */
-  case AccessibleAfterFirstUnlockThisDeviceOnly
-  
-  /**
-  
-  The data in the keychain item can always be accessed regardless of whether the device is locked.
-  
-  This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
-  
-  */
-  case AccessibleAlways
-  
-  /**
-  
-  The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
-  
-  This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
-  
-  */
-  case AccessibleWhenPasscodeSetThisDeviceOnly
-  
-  /**
-  
-  The data in the keychain item can always be accessed regardless of whether the device is locked.
-  
-  This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
-  
-  */
-  case AccessibleAlwaysThisDeviceOnly
-  
-  var value: String {
-    switch self {
-    case .AccessibleWhenUnlocked:
-      return toString(kSecAttrAccessibleWhenUnlocked)
-      
-    case .AccessibleWhenUnlockedThisDeviceOnly:
-      return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
-      
-    case .AccessibleAfterFirstUnlock:
-      return toString(kSecAttrAccessibleAfterFirstUnlock)
-      
-    case .AccessibleAfterFirstUnlockThisDeviceOnly:
-      return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
-      
-    case .AccessibleAlways:
-      return toString(kSecAttrAccessibleAlways)
-      
-    case .AccessibleWhenPasscodeSetThisDeviceOnly:
-      return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
-      
-    case .AccessibleAlwaysThisDeviceOnly:
-      return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
-    }
-  }
-  
-  func toString(value: CFStringRef) -> String {
+  static func toString(value: CFStringRef) -> String {
     return (value as? String) ?? ""
   }
 }

+ 0 - 3
keychain/TegKeychainOptions.swift

@@ -1,3 +0,0 @@
-//public struct TegKeychainOptions {
-//  public var accessible: TegKeychainAccessibilityConstants = .AccessibleWhenUnlocked
-//}

+ 1 - 6
keychainTests/keychainTests.swift

@@ -18,12 +18,7 @@ class keychainTests: XCTestCase {
   }
   
   func testSetWithOptions() {
-    let value = TegKeychainConstants.classGenericPassword
-    println("!!!!!!!!! \(value)")
-//    TegKeychain.set("key 1", value: "hello :)", options: [
-//      TegKeychainConstants.accesibility: 
-//    ]
-//    )
+    TegKeychain.set("key 1", value: "hello :)", withAccess: .AccessibleAfterFirstUnlock)
   }
 
   // Get