KeychainSwiftDistrib.swift 15 KB

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