KeychainSwiftDistrib.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. public class KeychainSwift {
  19. var lastQueryParameters: [String: NSObject]? // Used by the unit tests
  20. /// Contains result code from the last operation. Value is noErr (0) for a successful result.
  21. public 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. public var accessGroup: String?
  27. public init() { }
  28. /**
  29. - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
  30. */
  31. public init(keyPrefix: String) {
  32. self.keyPrefix = keyPrefix
  33. }
  34. /**
  35. Stores the text value in the keychain item under the given key.
  36. - parameter key: Key under which the text value is stored in the keychain.
  37. - parameter value: Text string to be written to the keychain.
  38. - 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.
  39. - returns: True if the text was successfully written to the keychain.
  40. */
  41. public func set(value: String, forKey key: String,
  42. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  43. if let value = value.dataUsingEncoding(NSUTF8StringEncoding) {
  44. return set(value, forKey: key, withAccess: access)
  45. }
  46. return false
  47. }
  48. /**
  49. Stores the data in the keychain item under the given key.
  50. - parameter key: Key under which the data is stored in the keychain.
  51. - parameter value: Data to be written to the keychain.
  52. - 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.
  53. - returns: True if the text was successfully written to the keychain.
  54. */
  55. public func set(value: NSData, forKey key: String,
  56. withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
  57. delete(key) // Delete any existing key before saving it
  58. let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
  59. let prefixedKey = keyWithPrefix(key)
  60. var query = [
  61. KeychainSwiftConstants.klass : KeychainSwiftConstants.classGenericPassword,
  62. KeychainSwiftConstants.attrAccount : prefixedKey,
  63. KeychainSwiftConstants.valueData : value,
  64. KeychainSwiftConstants.accessible : accessible
  65. ]
  66. query = addAccessGroupWhenPresent(query)
  67. lastQueryParameters = query
  68. lastResultCode = SecItemAdd(query as CFDictionaryRef, nil)
  69. return lastResultCode == noErr
  70. }
  71. /**
  72. Retrieves the text value from the keychain that corresponds to the given key.
  73. - parameter key: The key that is used to read the keychain item.
  74. - returns: The text value from the keychain. Returns nil if unable to read the item.
  75. */
  76. public func get(key: String) -> String? {
  77. if let data = getData(key) {
  78. if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
  79. return currentString
  80. }
  81. lastResultCode = -67853 // errSecInvalidEncoding
  82. }
  83. return nil
  84. }
  85. /**
  86. Retrieves the data from the keychain that corresponds to the given key.
  87. - parameter key: The key that is used to read the keychain item.
  88. - returns: The text value from the keychain. Returns nil if unable to read the item.
  89. */
  90. public func getData(key: String) -> NSData? {
  91. let prefixedKey = keyWithPrefix(key)
  92. var query: [String: NSObject] = [
  93. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  94. KeychainSwiftConstants.attrAccount : prefixedKey,
  95. KeychainSwiftConstants.returnData : kCFBooleanTrue,
  96. KeychainSwiftConstants.matchLimit : kSecMatchLimitOne ]
  97. query = addAccessGroupWhenPresent(query)
  98. lastQueryParameters = query
  99. var result: AnyObject?
  100. lastResultCode = withUnsafeMutablePointer(&result) {
  101. SecItemCopyMatching(query, UnsafeMutablePointer($0))
  102. }
  103. if lastResultCode == noErr { return result as? NSData }
  104. return nil
  105. }
  106. /**
  107. Deletes the single keychain item specified by the key.
  108. - parameter key: The key that is used to delete the keychain item.
  109. - returns: True if the item was successfully deleted.
  110. */
  111. public func delete(key: String) -> Bool {
  112. let prefixedKey = keyWithPrefix(key)
  113. var query: [String: NSObject] = [
  114. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  115. KeychainSwiftConstants.attrAccount : prefixedKey ]
  116. query = addAccessGroupWhenPresent(query)
  117. lastQueryParameters = query
  118. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  119. return lastResultCode == noErr
  120. }
  121. /**
  122. 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.
  123. - returns: True if the keychain items were successfully deleted.
  124. */
  125. public func clear() -> Bool {
  126. var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ]
  127. query = addAccessGroupWhenPresent(query)
  128. lastQueryParameters = query
  129. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  130. return lastResultCode == noErr
  131. }
  132. /// Returns the key with currently set prefix.
  133. func keyWithPrefix(key: String) -> String {
  134. return "\(keyPrefix)\(key)"
  135. }
  136. func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] {
  137. guard let accessGroup = accessGroup else { return items }
  138. var result: [String: NSObject] = items
  139. result[KeychainSwiftConstants.accessGroup] = accessGroup
  140. return result
  141. }
  142. }
  143. // ----------------------------
  144. //
  145. // KeychainSwiftAccessOptions.swift
  146. //
  147. // ----------------------------
  148. import Security
  149. /**
  150. These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
  151. */
  152. public enum KeychainSwiftAccessOptions {
  153. /**
  154. The data in the keychain item can be accessed only while the device is unlocked by the user.
  155. 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.
  156. This is the default value for keychain items added without explicitly setting an accessibility constant.
  157. */
  158. case AccessibleWhenUnlocked
  159. /**
  160. The data in the keychain item can be accessed only while the device is unlocked by the user.
  161. 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.
  162. */
  163. case AccessibleWhenUnlockedThisDeviceOnly
  164. /**
  165. The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
  166. 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.
  167. */
  168. case AccessibleAfterFirstUnlock
  169. /**
  170. The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
  171. 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.
  172. */
  173. case AccessibleAfterFirstUnlockThisDeviceOnly
  174. /**
  175. The data in the keychain item can always be accessed regardless of whether the device is locked.
  176. This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
  177. */
  178. case AccessibleAlways
  179. /**
  180. The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
  181. 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.
  182. */
  183. case AccessibleWhenPasscodeSetThisDeviceOnly
  184. /**
  185. The data in the keychain item can always be accessed regardless of whether the device is locked.
  186. 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.
  187. */
  188. case AccessibleAlwaysThisDeviceOnly
  189. static var defaultOption: KeychainSwiftAccessOptions {
  190. return .AccessibleWhenUnlocked
  191. }
  192. var value: String {
  193. switch self {
  194. case .AccessibleWhenUnlocked:
  195. return toString(kSecAttrAccessibleWhenUnlocked)
  196. case .AccessibleWhenUnlockedThisDeviceOnly:
  197. return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
  198. case .AccessibleAfterFirstUnlock:
  199. return toString(kSecAttrAccessibleAfterFirstUnlock)
  200. case .AccessibleAfterFirstUnlockThisDeviceOnly:
  201. return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
  202. case .AccessibleAlways:
  203. return toString(kSecAttrAccessibleAlways)
  204. case .AccessibleWhenPasscodeSetThisDeviceOnly:
  205. return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
  206. case .AccessibleAlwaysThisDeviceOnly:
  207. return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
  208. }
  209. }
  210. func toString(value: CFStringRef) -> String {
  211. return KeychainSwiftConstants.toString(value)
  212. }
  213. }
  214. // ----------------------------
  215. //
  216. // TegKeychainConstants.swift
  217. //
  218. // ----------------------------
  219. import Foundation
  220. import Security
  221. public struct KeychainSwiftConstants {
  222. public static var klass: String { return toString(kSecClass) }
  223. public static var classGenericPassword: String { return toString(kSecClassGenericPassword) }
  224. public static var attrAccount: String { return toString(kSecAttrAccount) }
  225. public static var valueData: String { return toString(kSecValueData) }
  226. public static var returnData: String { return toString(kSecReturnData) }
  227. public static var matchLimit: String { return toString(kSecMatchLimit) }
  228. public static var accessGroup: String { return toString(kSecAttrAccessGroup) }
  229. /**
  230. 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.
  231. */
  232. public static var accessible: String { return toString(kSecAttrAccessible) }
  233. static func toString(value: CFStringRef) -> String {
  234. return value as String
  235. }
  236. }