KeychainSwiftDistrib.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //
  2. // Keychain helper for iOS/Swift.
  3. //
  4. // https://github.com/evgenyneu/keychain-swift
  5. //
  6. // This file was automatically generated by combining multiple Swift source files.
  7. //
  8. // ----------------------------
  9. //
  10. // KeychainSwift.swift
  11. //
  12. // ----------------------------
  13. import Security
  14. import Foundation
  15. /**
  16. A collection of helper functions for saving text and data in the keychain.
  17. */
  18. open class KeychainSwift {
  19. var lastQueryParameters: [String: Any]? // Used by the unit tests
  20. /// Contains result code from the last operation. Value is noErr (0) for a successful result.
  21. open var lastResultCode: OSStatus = noErr
  22. var keyPrefix = "" // Can be useful in test.
  23. /**
  24. 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.
  25. */
  26. open var accessGroup: String?
  27. /**
  28. Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
  29. 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.
  30. Does not work on macOS.
  31. */
  32. open var synchronizable: Bool = false
  33. private let readLock = NSLock()
  34. /// Instantiate a KeychainSwift object
  35. public init() { }
  36. /**
  37. - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
  38. */
  39. public init(keyPrefix: String) {
  40. self.keyPrefix = keyPrefix
  41. }
  42. /**
  43. Stores the text value in the keychain item under the given key.
  44. - parameter key: Key under which the text value is stored in the keychain.
  45. - parameter value: Text string 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. @discardableResult
  50. open func set(_ value: String, forKey key: String,
  51. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  52. if let value = value.data(using: String.Encoding.utf8) {
  53. return set(value, forKey: key, withAccess: access)
  54. }
  55. return false
  56. }
  57. /**
  58. Stores the data in the keychain item under the given key.
  59. - parameter key: Key under which the data is stored in the keychain.
  60. - parameter value: Data to be written to the keychain.
  61. - 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.
  62. - returns: True if the text was successfully written to the keychain.
  63. */
  64. @discardableResult
  65. open func set(_ value: Data, forKey key: String,
  66. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  67. delete(key) // Delete any existing key before saving it
  68. let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
  69. let prefixedKey = keyWithPrefix(key)
  70. var query: [String : Any] = [
  71. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  72. KeychainSwiftConstants.attrAccount : prefixedKey,
  73. KeychainSwiftConstants.valueData : value,
  74. KeychainSwiftConstants.accessible : accessible
  75. ]
  76. query = addAccessGroupWhenPresent(query)
  77. query = addSynchronizableIfRequired(query, addingItems: true)
  78. lastQueryParameters = query
  79. lastResultCode = SecItemAdd(query as CFDictionary, nil)
  80. return lastResultCode == noErr
  81. }
  82. /**
  83. Stores the boolean value in the keychain item under the given key.
  84. - parameter key: Key under which the value is stored in the keychain.
  85. - parameter value: Boolean to be written to the keychain.
  86. - 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.
  87. - returns: True if the value was successfully written to the keychain.
  88. */
  89. @discardableResult
  90. open func set(_ value: Bool, forKey key: String,
  91. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  92. let bytes: [UInt8] = value ? [1] : [0]
  93. let data = Data(bytes: bytes)
  94. return set(data, forKey: key, withAccess: access)
  95. }
  96. /**
  97. Retrieves the text value from the keychain that corresponds to the given key.
  98. - parameter key: The key that is used to read the keychain item.
  99. - returns: The text value from the keychain. Returns nil if unable to read the item.
  100. */
  101. open func get(_ key: String) -> String? {
  102. if let data = getData(key) {
  103. if let currentString = String(data: data, encoding: .utf8) {
  104. return currentString
  105. }
  106. lastResultCode = -67853 // errSecInvalidEncoding
  107. }
  108. return nil
  109. }
  110. /**
  111. Retrieves the data from the keychain that corresponds to the given key.
  112. - parameter key: The key that is used to read the keychain item.
  113. - returns: The text value from the keychain. Returns nil if unable to read the item.
  114. */
  115. open func getData(_ key: String) -> Data? {
  116. // The lock prevents the code to be run simlultaneously
  117. // from multiple threads which may result in crashing
  118. readLock.lock()
  119. defer { readLock.unlock() }
  120. let prefixedKey = keyWithPrefix(key)
  121. var query: [String: Any] = [
  122. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  123. KeychainSwiftConstants.attrAccount : prefixedKey,
  124. KeychainSwiftConstants.returnData : kCFBooleanTrue,
  125. KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
  126. ]
  127. query = addAccessGroupWhenPresent(query)
  128. query = addSynchronizableIfRequired(query, addingItems: false)
  129. lastQueryParameters = query
  130. var result: AnyObject?
  131. lastResultCode = withUnsafeMutablePointer(to: &result) {
  132. SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
  133. }
  134. if lastResultCode == noErr { return result as? Data }
  135. return nil
  136. }
  137. /**
  138. Retrieves the boolean value from the keychain that corresponds to the given key.
  139. - parameter key: The key that is used to read the keychain item.
  140. - returns: The boolean value from the keychain. Returns nil if unable to read the item.
  141. */
  142. open func getBool(_ key: String) -> Bool? {
  143. guard let data = getData(key) else { return nil }
  144. guard let firstBit = data.first else { return nil }
  145. return firstBit == 1
  146. }
  147. /**
  148. Deletes the single keychain item specified by the key.
  149. - parameter key: The key that is used to delete the keychain item.
  150. - returns: True if the item was successfully deleted.
  151. */
  152. @discardableResult
  153. open func delete(_ key: String) -> Bool {
  154. let prefixedKey = keyWithPrefix(key)
  155. var query: [String: Any] = [
  156. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  157. KeychainSwiftConstants.attrAccount : prefixedKey
  158. ]
  159. query = addAccessGroupWhenPresent(query)
  160. query = addSynchronizableIfRequired(query, addingItems: false)
  161. lastQueryParameters = query
  162. lastResultCode = SecItemDelete(query as CFDictionary)
  163. return lastResultCode == noErr
  164. }
  165. /**
  166. 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.
  167. - returns: True if the keychain items were successfully deleted.
  168. */
  169. @discardableResult
  170. open func clear() -> Bool {
  171. var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ]
  172. query = addAccessGroupWhenPresent(query)
  173. query = addSynchronizableIfRequired(query, addingItems: false)
  174. lastQueryParameters = query
  175. lastResultCode = SecItemDelete(query as CFDictionary)
  176. return lastResultCode == noErr
  177. }
  178. /// Returns the key with currently set prefix.
  179. func keyWithPrefix(_ key: String) -> String {
  180. return "\(keyPrefix)\(key)"
  181. }
  182. func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] {
  183. guard let accessGroup = accessGroup else { return items }
  184. var result: [String: Any] = items
  185. result[KeychainSwiftConstants.accessGroup] = accessGroup
  186. return result
  187. }
  188. /**
  189. Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
  190. - parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
  191. - parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
  192. - returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
  193. */
  194. func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] {
  195. if !synchronizable { return items }
  196. var result: [String: Any] = items
  197. result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
  198. return result
  199. }
  200. }
  201. // ----------------------------
  202. //
  203. // TegKeychainConstants.swift
  204. //
  205. // ----------------------------
  206. import Foundation
  207. import Security
  208. /// Constants used by the library
  209. public struct KeychainSwiftConstants {
  210. /// Specifies a Keychain access group. Used for sharing Keychain items between apps.
  211. public static var accessGroup: String { return toString(kSecAttrAccessGroup) }
  212. /**
  213. 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 KeychainSwiftAccessOptions.
  214. */
  215. public static var accessible: String { return toString(kSecAttrAccessible) }
  216. /// Used for specifying a String key when setting/getting a Keychain value.
  217. public static var attrAccount: String { return toString(kSecAttrAccount) }
  218. /// Used for specifying synchronization of keychain items between devices.
  219. public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) }
  220. /// An item class key used to construct a Keychain search dictionary.
  221. public static var klass: String { return toString(kSecClass) }
  222. /// Specifies the number of values returned from the keychain. The library only supports single values.
  223. public static var matchLimit: String { return toString(kSecMatchLimit) }
  224. /// A return data type used to get the data from the Keychain.
  225. public static var returnData: String { return toString(kSecReturnData) }
  226. /// Used for specifying a value when setting a Keychain value.
  227. public static var valueData: String { return toString(kSecValueData) }
  228. static func toString(_ value: CFString) -> String {
  229. return value as String
  230. }
  231. }
  232. // ----------------------------
  233. //
  234. // KeychainSwiftAccessOptions.swift
  235. //
  236. // ----------------------------
  237. import Security
  238. /**
  239. These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
  240. */
  241. public enum KeychainSwiftAccessOptions {
  242. /**
  243. The data in the keychain item can be accessed only while the device is unlocked by the user.
  244. 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.
  245. This is the default value for keychain items added without explicitly setting an accessibility constant.
  246. */
  247. case accessibleWhenUnlocked
  248. /**
  249. The data in the keychain item can be accessed only while the device is unlocked by the user.
  250. 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.
  251. */
  252. case accessibleWhenUnlockedThisDeviceOnly
  253. /**
  254. The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
  255. 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.
  256. */
  257. case accessibleAfterFirstUnlock
  258. /**
  259. The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
  260. 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.
  261. */
  262. case accessibleAfterFirstUnlockThisDeviceOnly
  263. /**
  264. The data in the keychain item can always be accessed regardless of whether the device is locked.
  265. This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
  266. */
  267. case accessibleAlways
  268. /**
  269. The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
  270. 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.
  271. */
  272. case accessibleWhenPasscodeSetThisDeviceOnly
  273. /**
  274. The data in the keychain item can always be accessed regardless of whether the device is locked.
  275. 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.
  276. */
  277. case accessibleAlwaysThisDeviceOnly
  278. static var defaultOption: KeychainSwiftAccessOptions {
  279. return .accessibleWhenUnlocked
  280. }
  281. var value: String {
  282. switch self {
  283. case .accessibleWhenUnlocked:
  284. return toString(kSecAttrAccessibleWhenUnlocked)
  285. case .accessibleWhenUnlockedThisDeviceOnly:
  286. return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
  287. case .accessibleAfterFirstUnlock:
  288. return toString(kSecAttrAccessibleAfterFirstUnlock)
  289. case .accessibleAfterFirstUnlockThisDeviceOnly:
  290. return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
  291. case .accessibleAlways:
  292. return toString(kSecAttrAccessibleAlways)
  293. case .accessibleWhenPasscodeSetThisDeviceOnly:
  294. return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
  295. case .accessibleAlwaysThisDeviceOnly:
  296. return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
  297. }
  298. }
  299. func toString(_ value: CFString) -> String {
  300. return KeychainSwiftConstants.toString(value)
  301. }
  302. }