KeychainSwiftDistrib.swift 11 KB

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