KeychainSwiftDistrib.swift 10 KB

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