KeychainSwift.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import Security
  2. import Foundation
  3. /**
  4. A collection of helper functions for saving text and data in the keychain.
  5. */
  6. public class KeychainSwift {
  7. var lastQueryParameters: [String: NSObject]? // Used by the unit tests
  8. /// Contains result code from the last operation. Value is noErr (0) for a successful result.
  9. public var lastResultCode: OSStatus = noErr
  10. var keyPrefix = "" // Can be useful in test.
  11. /**
  12. Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear.
  13. */
  14. public var accessGroup: String?
  15. /**
  16. Specifies whether the items can be synchronized with other devices. Setting this property to true will
  17. add the item to other devices with the `set` method, obtain synchronizable items with `get` command. Deleting synchronizable items will remove them from all devices.
  18. */
  19. public var synchronizable: Bool = false
  20. /// Instantiate a KeychainSwift object
  21. public init() { }
  22. /**
  23. - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
  24. */
  25. public init(keyPrefix: String) {
  26. self.keyPrefix = keyPrefix
  27. }
  28. /**
  29. Stores the text value in the keychain item under the given key.
  30. - parameter key: Key under which the text value is stored in the keychain.
  31. - parameter value: Text string to be written to the keychain.
  32. - parameter 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.
  33. - returns: True if the text was successfully written to the keychain.
  34. */
  35. public func set(value: String, forKey key: String,
  36. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  37. if let value = value.dataUsingEncoding(NSUTF8StringEncoding) {
  38. return set(value, forKey: key, withAccess: access)
  39. }
  40. return false
  41. }
  42. /**
  43. Stores the data in the keychain item under the given key.
  44. - parameter key: Key under which the data is stored in the keychain.
  45. - parameter value: Data to be written to the keychain.
  46. - parameter 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.
  47. - returns: True if the text was successfully written to the keychain.
  48. */
  49. public func set(value: NSData, forKey key: String,
  50. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  51. delete(key) // Delete any existing key before saving it
  52. let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
  53. let prefixedKey = keyWithPrefix(key)
  54. var query = [
  55. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  56. KeychainSwiftConstants.attrAccount : prefixedKey,
  57. KeychainSwiftConstants.valueData : value,
  58. KeychainSwiftConstants.accessible : accessible //,
  59. // KeychainSwiftConstants.attrSynchronizable: false
  60. ]
  61. query = addAccessGroupWhenPresent(query)
  62. lastQueryParameters = query
  63. lastResultCode = SecItemAdd(query as CFDictionaryRef, nil)
  64. return lastResultCode == noErr
  65. }
  66. /**
  67. Stores the boolean value in the keychain item under the given key.
  68. - parameter key: Key under which the value is stored in the keychain.
  69. - parameter value: Boolean to be written to the keychain.
  70. - parameter withAccess: Value that indicates when your app needs access to the value 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.
  71. - returns: True if the value was successfully written to the keychain.
  72. */
  73. public func set(value: Bool, forKey key: String,
  74. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  75. var localValue = value
  76. let data = NSData(bytes: &localValue, length: sizeof(Bool))
  77. return set(data, forKey: key, withAccess: access)
  78. }
  79. /**
  80. Retrieves the text value from the keychain that corresponds to the given key.
  81. - parameter key: The key that is used to read the keychain item.
  82. - returns: The text value from the keychain. Returns nil if unable to read the item.
  83. */
  84. public func get(key: String) -> String? {
  85. if let data = getData(key) {
  86. if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
  87. return currentString
  88. }
  89. lastResultCode = -67853 // errSecInvalidEncoding
  90. }
  91. return nil
  92. }
  93. /**
  94. Retrieves the data from the keychain that corresponds to the given key.
  95. - parameter key: The key that is used to read the keychain item.
  96. - returns: The text value from the keychain. Returns nil if unable to read the item.
  97. */
  98. public func getData(key: String) -> NSData? {
  99. let prefixedKey = keyWithPrefix(key)
  100. var query: [String: NSObject] = [
  101. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  102. KeychainSwiftConstants.attrAccount : prefixedKey,
  103. KeychainSwiftConstants.returnData : kCFBooleanTrue,
  104. KeychainSwiftConstants.matchLimit : kSecMatchLimitOne //,
  105. // KeychainSwiftConstants.attrSynchronizable: kSecAttrSynchronizableAny
  106. ]
  107. query = addAccessGroupWhenPresent(query)
  108. lastQueryParameters = query
  109. var result: AnyObject?
  110. lastResultCode = withUnsafeMutablePointer(&result) {
  111. SecItemCopyMatching(query, UnsafeMutablePointer($0))
  112. }
  113. if lastResultCode == noErr { return result as? NSData }
  114. return nil
  115. }
  116. /**
  117. Retrieves the boolean value from the keychain that corresponds to the given key.
  118. - parameter key: The key that is used to read the keychain item.
  119. - returns: The boolean value from the keychain. Returns nil if unable to read the item.
  120. */
  121. public func getBool(key: String) -> Bool? {
  122. guard let data = getData(key) else { return nil }
  123. var boolValue = false
  124. data.getBytes(&boolValue, length: sizeof(Bool))
  125. return boolValue
  126. }
  127. /**
  128. Deletes the single keychain item specified by the key.
  129. - parameter key: The key that is used to delete the keychain item.
  130. - returns: True if the item was successfully deleted.
  131. */
  132. public func delete(key: String) -> Bool {
  133. let prefixedKey = keyWithPrefix(key)
  134. var query: [String: NSObject] = [
  135. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  136. KeychainSwiftConstants.attrAccount : prefixedKey //,
  137. // KeychainSwiftConstants.attrSynchronizable: kSecAttrSynchronizableAny
  138. ]
  139. query = addAccessGroupWhenPresent(query)
  140. lastQueryParameters = query
  141. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  142. return lastResultCode == noErr
  143. }
  144. /**
  145. Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class.
  146. - returns: True if the keychain items were successfully deleted.
  147. */
  148. public func clear() -> Bool {
  149. var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ]
  150. query = addAccessGroupWhenPresent(query)
  151. lastQueryParameters = query
  152. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  153. return lastResultCode == noErr
  154. }
  155. /// Returns the key with currently set prefix.
  156. func keyWithPrefix(key: String) -> String {
  157. return "\(keyPrefix)\(key)"
  158. }
  159. func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] {
  160. guard let accessGroup = accessGroup else { return items }
  161. var result: [String: NSObject] = items
  162. result[KeychainSwiftConstants.accessGroup] = accessGroup
  163. return result
  164. }
  165. /// Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny items to the dictionary when the `synchronizable` property is true.
  166. func addSynchronizableIfRequired(items: [String: NSObject]) -> [String: NSObject] {
  167. if !synchronizable { return items }
  168. var result: [String: NSObject] = items
  169. result[KeychainSwiftConstants.attrSynchronizable] = kSecAttrSynchronizableAny
  170. return result
  171. }
  172. }