KeychainSwift.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import Security
  2. import Foundation
  3. /**
  4. A collection of helper functions for saving text and data in the keychain.
  5. */
  6. public class KeychainSwift {
  7. var lastQueryParameters: [String: NSObject]? // Used by the unit tests
  8. /// Contains result code from the last operation. Value is noErr (0) for a successful result.
  9. public var lastResultCode: OSStatus = noErr
  10. var keyPrefix = "" // Can be useful in test.
  11. /**
  12. 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.
  13. */
  14. public var accessGroup: String?
  15. /// Instantiate a KeychainSwift object
  16. public init() { }
  17. /**
  18. - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
  19. */
  20. public init(keyPrefix: String) {
  21. self.keyPrefix = keyPrefix
  22. }
  23. /**
  24. Stores the text value in the keychain item under the given key.
  25. - parameter key: Key under which the text value is stored in the keychain.
  26. - parameter value: Text string to be written to the keychain.
  27. - 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.
  28. - parameter synchronize: Value indicating if keychain item should be synced over iCloud
  29. - returns: True if the text was successfully written to the keychain.
  30. */
  31. public func set(value: String, forKey key: String,
  32. withAccess access: KeychainSwiftAccessOptions? = nil, synchronize: Bool = false) -> Bool {
  33. if let value = value.dataUsingEncoding(NSUTF8StringEncoding) {
  34. return set(value, forKey: key, withAccess: access, synchronize: synchronize)
  35. }
  36. return false
  37. }
  38. /**
  39. Stores the data in the keychain item under the given key.
  40. - parameter key: Key under which the data is stored in the keychain.
  41. - parameter value: Data to be written to the keychain.
  42. - 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.
  43. - parameter synchronize: Value indicating if keychain item should be synced over iCloud
  44. - returns: True if the text was successfully written to the keychain.
  45. */
  46. public func set(value: NSData, forKey key: String,
  47. withAccess access: KeychainSwiftAccessOptions? = nil, synchronize: Bool = false) -> Bool {
  48. delete(key) // Delete any existing key before saving it
  49. let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
  50. let prefixedKey = keyWithPrefix(key)
  51. var query = [
  52. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  53. KeychainSwiftConstants.attrAccount : prefixedKey,
  54. KeychainSwiftConstants.valueData : value,
  55. KeychainSwiftConstants.accessible : accessible,
  56. KeychainSwiftConstants.attrSynchronizable: synchronize
  57. ]
  58. query = addAccessGroupWhenPresent(query)
  59. lastQueryParameters = query
  60. lastResultCode = SecItemAdd(query as CFDictionaryRef, nil)
  61. return lastResultCode == noErr
  62. }
  63. /**
  64. Stores the boolean value in the keychain item under the given key.
  65. - parameter key: Key under which the value is stored in the keychain.
  66. - parameter value: Boolean to be written to the keychain.
  67. - 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.
  68. - parameter synchronize: Value indicating if keychain item should be synced over iCloud
  69. - returns: True if the value was successfully written to the keychain.
  70. */
  71. public func set(value: Bool, forKey key: String,
  72. withAccess access: KeychainSwiftAccessOptions? = nil, synchronize: Bool = false) -> Bool {
  73. var localValue = value
  74. let data = NSData(bytes: &localValue, length: sizeof(Bool))
  75. return set(data, forKey: key, withAccess: access, synchronize: synchronize)
  76. }
  77. /**
  78. Retrieves the text value from the keychain that corresponds to the given key.
  79. - parameter key: The key that is used to read the keychain item.
  80. - returns: The text value from the keychain. Returns nil if unable to read the item.
  81. */
  82. public func get(key: String) -> String? {
  83. if let data = getData(key) {
  84. if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
  85. return currentString
  86. }
  87. lastResultCode = -67853 // errSecInvalidEncoding
  88. }
  89. return nil
  90. }
  91. /**
  92. Retrieves the data from the keychain that corresponds to the given key.
  93. - parameter key: The key that is used to read the keychain item.
  94. - returns: The text value from the keychain. Returns nil if unable to read the item.
  95. */
  96. public func getData(key: String) -> NSData? {
  97. let prefixedKey = keyWithPrefix(key)
  98. var query: [String: NSObject] = [
  99. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  100. KeychainSwiftConstants.attrAccount : prefixedKey,
  101. KeychainSwiftConstants.returnData : kCFBooleanTrue,
  102. KeychainSwiftConstants.matchLimit : kSecMatchLimitOne,
  103. KeychainSwiftConstants.attrSynchronizable: kSecAttrSynchronizableAny
  104. ]
  105. query = addAccessGroupWhenPresent(query)
  106. lastQueryParameters = query
  107. var result: AnyObject?
  108. lastResultCode = withUnsafeMutablePointer(&result) {
  109. SecItemCopyMatching(query, UnsafeMutablePointer($0))
  110. }
  111. if lastResultCode == noErr { return result as? NSData }
  112. return nil
  113. }
  114. /**
  115. Retrieves the boolean value from the keychain that corresponds to the given key.
  116. - parameter key: The key that is used to read the keychain item.
  117. - returns: The boolean value from the keychain. Returns nil if unable to read the item.
  118. */
  119. public func getBool(key: String) -> Bool? {
  120. guard let data = getData(key) else { return nil }
  121. var boolValue = false
  122. data.getBytes(&boolValue, length: sizeof(Bool))
  123. return boolValue
  124. }
  125. /**
  126. Deletes the single keychain item specified by the key.
  127. - parameter key: The key that is used to delete the keychain item.
  128. - returns: True if the item was successfully deleted.
  129. */
  130. public func delete(key: String) -> Bool {
  131. let prefixedKey = keyWithPrefix(key)
  132. var query: [String: NSObject] = [
  133. KeychainSwiftConstants.klass : kSecClassGenericPassword,
  134. KeychainSwiftConstants.attrAccount : prefixedKey,
  135. KeychainSwiftConstants.attrSynchronizable: kSecAttrSynchronizableAny
  136. ]
  137. query = addAccessGroupWhenPresent(query)
  138. lastQueryParameters = query
  139. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  140. return lastResultCode == noErr
  141. }
  142. /**
  143. 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.
  144. - returns: True if the keychain items were successfully deleted.
  145. */
  146. public func clear() -> Bool {
  147. var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ]
  148. query = addAccessGroupWhenPresent(query)
  149. lastQueryParameters = query
  150. lastResultCode = SecItemDelete(query as CFDictionaryRef)
  151. return lastResultCode == noErr
  152. }
  153. /// Returns the key with currently set prefix.
  154. func keyWithPrefix(key: String) -> String {
  155. return "\(keyPrefix)\(key)"
  156. }
  157. func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] {
  158. guard let accessGroup = accessGroup else { return items }
  159. var result: [String: NSObject] = items
  160. result[KeychainSwiftConstants.accessGroup] = accessGroup
  161. return result
  162. }
  163. }