KeychainSwift.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import Security
  2. import Foundation
  3. /**
  4. A collection of helper functions for saving text and data in the keychain.
  5. */
  6. open class KeychainSwift {
  7. var lastQueryParameters: [String: Any]? // Used by the unit tests
  8. /// Contains result code from the last operation. Value is noErr (0) for a successful result.
  9. open 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. open var accessGroup: String?
  15. /**
  16. Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
  17. add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings.
  18. Does not work on macOS.
  19. */
  20. open var synchronizable: Bool = false
  21. private let lock = NSLock()
  22. /// Instantiate a KeychainSwift object
  23. public init() { }
  24. /**
  25. - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
  26. */
  27. public init(keyPrefix: String) {
  28. self.keyPrefix = keyPrefix
  29. }
  30. /**
  31. Stores the text value in the keychain item under the given key.
  32. - parameter key: Key under which the text value is stored in the keychain.
  33. - parameter value: Text string to be written to the keychain.
  34. - 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.
  35. - returns: True if the text was successfully written to the keychain.
  36. */
  37. @discardableResult
  38. open func set(_ value: String, forKey key: String,
  39. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  40. if let value = value.data(using: String.Encoding.utf8) {
  41. return set(value, forKey: key, withAccess: access)
  42. }
  43. return false
  44. }
  45. /**
  46. Stores the data in the keychain item under the given key.
  47. - parameter key: Key under which the data is stored in the keychain.
  48. - parameter value: Data to be written to the keychain.
  49. - 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.
  50. - returns: True if the text was successfully written to the keychain.
  51. */
  52. @discardableResult
  53. open func set(_ value: Data, forKey key: String,
  54. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  55. // The lock prevents the code to be run simlultaneously
  56. // from multiple threads which may result in crashing
  57. lock.lock()
  58. defer { lock.unlock() }
  59. deleteNoLock(key) // Delete any existing key before saving it
  60. let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
  61. let prefixedKey = keyWithPrefix(key)
  62. var query: [String : Any] = [
  63. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  64. KeychainSwiftConstants.attrAccount : prefixedKey,
  65. KeychainSwiftConstants.valueData : value,
  66. KeychainSwiftConstants.accessible : accessible
  67. ]
  68. query = addAccessGroupWhenPresent(query)
  69. query = addSynchronizableIfRequired(query, addingItems: true)
  70. lastQueryParameters = query
  71. lastResultCode = SecItemAdd(query as CFDictionary, nil)
  72. return lastResultCode == noErr
  73. }
  74. /**
  75. Stores the boolean value in the keychain item under the given key.
  76. - parameter key: Key under which the value is stored in the keychain.
  77. - parameter value: Boolean to be written to the keychain.
  78. - 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.
  79. - returns: True if the value was successfully written to the keychain.
  80. */
  81. @discardableResult
  82. open func set(_ value: Bool, forKey key: String,
  83. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  84. let bytes: [UInt8] = value ? [1] : [0]
  85. let data = Data(bytes)
  86. return set(data, forKey: key, withAccess: access)
  87. }
  88. /**
  89. Retrieves the text value from the keychain that corresponds to the given key.
  90. - parameter key: The key that is used to read the keychain item.
  91. - returns: The text value from the keychain. Returns nil if unable to read the item.
  92. */
  93. open func get(_ key: String) -> String? {
  94. if let data = getData(key) {
  95. if let currentString = String(data: data, encoding: .utf8) {
  96. return currentString
  97. }
  98. lastResultCode = -67853 // errSecInvalidEncoding
  99. }
  100. return nil
  101. }
  102. /**
  103. Retrieves the data from the keychain that corresponds to the given key.
  104. - parameter key: The key that is used to read the keychain item.
  105. - parameter asReference: If true, returns the data as reference (needed for things like NEVPNProtocol).
  106. - returns: The text value from the keychain. Returns nil if unable to read the item.
  107. */
  108. open func getData(_ key: String, asReference: Bool = false) -> Data? {
  109. // The lock prevents the code to be run simlultaneously
  110. // from multiple threads which may result in crashing
  111. lock.lock()
  112. defer { lock.unlock() }
  113. let prefixedKey = keyWithPrefix(key)
  114. var query: [String: Any] = [
  115. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  116. KeychainSwiftConstants.attrAccount : prefixedKey,
  117. KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
  118. ]
  119. if asReference {
  120. query[KeychainSwiftConstants.returnReference] = kCFBooleanTrue
  121. } else {
  122. query[KeychainSwiftConstants.returnData] = kCFBooleanTrue
  123. }
  124. query = addAccessGroupWhenPresent(query)
  125. query = addSynchronizableIfRequired(query, addingItems: false)
  126. lastQueryParameters = query
  127. var result: AnyObject?
  128. lastResultCode = withUnsafeMutablePointer(to: &result) {
  129. SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
  130. }
  131. if lastResultCode == noErr {
  132. return result as? Data
  133. }
  134. return nil
  135. }
  136. /**
  137. Retrieves the boolean value from the keychain that corresponds to the given key.
  138. - parameter key: The key that is used to read the keychain item.
  139. - returns: The boolean value from the keychain. Returns nil if unable to read the item.
  140. */
  141. open func getBool(_ key: String) -> Bool? {
  142. guard let data = getData(key) else { return nil }
  143. guard let firstBit = data.first else { return nil }
  144. return firstBit == 1
  145. }
  146. /**
  147. Deletes the single keychain item specified by the key.
  148. - parameter key: The key that is used to delete the keychain item.
  149. - returns: True if the item was successfully deleted.
  150. */
  151. @discardableResult
  152. open func delete(_ key: String) -> Bool {
  153. // The lock prevents the code to be run simlultaneously
  154. // from multiple threads which may result in crashing
  155. lock.lock()
  156. defer { lock.unlock() }
  157. return deleteNoLock(key)
  158. }
  159. /**
  160. Same as `delete` but is only accessed internally, since it is not thread safe.
  161. - parameter key: The key that is used to delete the keychain item.
  162. - returns: True if the item was successfully deleted.
  163. */
  164. @discardableResult
  165. func deleteNoLock(_ key: String) -> Bool {
  166. let prefixedKey = keyWithPrefix(key)
  167. var query: [String: Any] = [
  168. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  169. KeychainSwiftConstants.attrAccount : prefixedKey
  170. ]
  171. query = addAccessGroupWhenPresent(query)
  172. query = addSynchronizableIfRequired(query, addingItems: false)
  173. lastQueryParameters = query
  174. lastResultCode = SecItemDelete(query as CFDictionary)
  175. return lastResultCode == noErr
  176. }
  177. /**
  178. 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.
  179. - returns: True if the keychain items were successfully deleted.
  180. */
  181. @discardableResult
  182. @available(macOS, unavailable, message: "Not implemented on macOS, call delete for every key.")
  183. open func clear() -> Bool {
  184. // The lock prevents the code to be run simlultaneously
  185. // from multiple threads which may result in crashing
  186. lock.lock()
  187. defer { lock.unlock() }
  188. var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ]
  189. query = addAccessGroupWhenPresent(query)
  190. query = addSynchronizableIfRequired(query, addingItems: false)
  191. lastQueryParameters = query
  192. lastResultCode = SecItemDelete(query as CFDictionary)
  193. return lastResultCode == noErr
  194. }
  195. /// Returns the key with currently set prefix.
  196. func keyWithPrefix(_ key: String) -> String {
  197. return "\(keyPrefix)\(key)"
  198. }
  199. func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] {
  200. guard let accessGroup = accessGroup else { return items }
  201. var result: [String: Any] = items
  202. result[KeychainSwiftConstants.accessGroup] = accessGroup
  203. return result
  204. }
  205. /**
  206. Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
  207. - parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
  208. - parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
  209. - returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
  210. */
  211. func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] {
  212. if !synchronizable { return items }
  213. var result: [String: Any] = items
  214. result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
  215. return result
  216. }
  217. }