Skip to content
This repository was archived by the owner on Jan 10, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion SwiftKeychainWrapper.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Pod::Spec.new do |s|
s.homepage = 'https://github.com/jrendel/SwiftKeychainWrapper'
s.license = 'MIT'
s.authors = { 'Jason Rendel' => '[email protected]' }
s.ios.deployment_target = '9.0'
s.ios.deployment_target = '11.0'
s.tvos.deployment_target = '11.0'
s.swift_version = ['4.2', '5.0']
s.source = { :git => 'https://github.com/jrendel/SwiftKeychainWrapper.git', :tag => s.version }
Expand Down
6 changes: 3 additions & 3 deletions SwiftKeychainWrapper.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@
attributes = {
LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0810;
LastUpgradeCheck = 1200;
LastUpgradeCheck = 1250;
ORGANIZATIONNAME = "Jason Rendel";
TargetAttributes = {
47E429C51DCCE2FD002BE498 = {
Expand Down Expand Up @@ -488,7 +488,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
ONLY_ACTIVE_ARCH = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
Expand Down Expand Up @@ -526,7 +526,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1250"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
18 changes: 4 additions & 14 deletions SwiftKeychainWrapper/KeychainItemAccessibility.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,32 +92,22 @@ public enum KeychainItemAccessibility {
case whenUnlockedThisDeviceOnly

static func accessibilityForAttributeValue(_ keychainAttrValue: CFString) -> KeychainItemAccessibility? {
for (key, value) in keychainItemAccessibilityLookup {
if value == keychainAttrValue {
return key
}
}

return nil
keychainItemAccessibilityLookup.first { $0.value == keychainAttrValue }?.key
}
}

private let keychainItemAccessibilityLookup: [KeychainItemAccessibility:CFString] = {
var lookup: [KeychainItemAccessibility:CFString] = [
return [
.afterFirstUnlock: kSecAttrAccessibleAfterFirstUnlock,
.afterFirstUnlockThisDeviceOnly: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
.always: kSecAttrAccessibleAlways,
.whenPasscodeSetThisDeviceOnly: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.alwaysThisDeviceOnly : kSecAttrAccessibleAlwaysThisDeviceOnly,
.whenUnlocked: kSecAttrAccessibleWhenUnlocked,
.whenUnlockedThisDeviceOnly: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]

return lookup
}()

extension KeychainItemAccessibility : KeychainAttrRepresentable {
internal var keychainAttrValue: CFString {
return keychainItemAccessibilityLookup[self]!
var keychainAttrValue: CFString {
keychainItemAccessibilityLookup[self]!
}
}
105 changes: 31 additions & 74 deletions SwiftKeychainWrapper/KeychainWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ open class KeychainWrapper {
/// AccessGroup is used for the kSecAttrAccessGroup property to identify which Keychain Access Group this entry belongs to. This allows you to use the KeychainWrapper with shared keychain access between different applications.
private (set) public var accessGroup: String?

private static let defaultServiceName: String = {
return Bundle.main.bundleIdentifier ?? "SwiftKeychainWrapper"
}()
private static let defaultServiceName = Bundle.main.bundleIdentifier ?? "SwiftKeychainWrapper"

private convenience init() {
self.init(serviceName: KeychainWrapper.defaultServiceName)
Expand All @@ -82,11 +80,7 @@ open class KeychainWrapper {
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if a value exists for the key. False otherwise.
open func hasValue(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
if let _ = data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) {
return true
} else {
return false
}
data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) != nil
}

open func accessibilityOfKey(_ key: String) -> KeychainItemAccessibility? {
Expand All @@ -109,7 +103,7 @@ open class KeychainWrapper {
return nil
}

return KeychainItemAccessibility.accessibilityForAttributeValue(accessibilityAttrValue as CFString)
return .accessibilityForAttributeValue(accessibilityAttrValue as CFString)
}

/// Get the keys of all keychain entries matching the current ServiceName and AccessGroup if one is set.
Expand Down Expand Up @@ -148,35 +142,19 @@ open class KeychainWrapper {
// MARK: Public Getters

open func integer(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Int? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}

return numberValue.intValue
object(forKey: key, ofClass: NSNumber.self, withAccessibility: accessibility, isSynchronizable: isSynchronizable)?.intValue
}

open func float(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Float? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}

return numberValue.floatValue
object(forKey: key, ofClass: NSNumber.self, withAccessibility: accessibility, isSynchronizable: isSynchronizable)?.floatValue
}

open func double(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Double? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}

return numberValue.doubleValue
object(forKey: key, ofClass: NSNumber.self, withAccessibility: accessibility, isSynchronizable: isSynchronizable)?.doubleValue
}

open func bool(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}

return numberValue.boolValue
object(forKey: key, ofClass: NSNumber.self, withAccessibility: accessibility, isSynchronizable: isSynchronizable)?.boolValue
}

/// Returns a string value for a specified key.
Expand All @@ -190,7 +168,7 @@ open class KeychainWrapper {
return nil
}

return String(data: keychainData, encoding: String.Encoding.utf8) as String?
return String(data: keychainData, encoding: .utf8)
}

/// Returns an object that conforms to NSCoding for a specified key.
Expand All @@ -199,12 +177,12 @@ open class KeychainWrapper {
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: The decoded object associated with the key if it exists. If no data exists, or the data found cannot be decoded, returns nil.
open func object(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> NSCoding? {
open func object<DecodedObjectType>(forKey key: String, ofClass cls: DecodedObjectType.Type, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> DecodedObjectType? where DecodedObjectType : NSObject, DecodedObjectType : NSCoding {
guard let keychainData = data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) else {
return nil
}

return NSKeyedUnarchiver.unarchiveObject(with: keychainData) as? NSCoding
return try? NSKeyedUnarchiver.unarchivedObject(ofClass: cls, from: keychainData)
}


Expand Down Expand Up @@ -256,19 +234,19 @@ open class KeychainWrapper {
// MARK: Public Setters

@discardableResult open func set(_ value: Int, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

@discardableResult open func set(_ value: Float, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

@discardableResult open func set(_ value: Double, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

@discardableResult open func set(_ value: Bool, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

/// Save a String value to the keychain associated with a specified key. If a String value already exists for the given key, the string will be overwritten with the new value.
Expand All @@ -279,11 +257,8 @@ open class KeychainWrapper {
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: String, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
if let data = value.data(using: .utf8) {
return set(data, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
} else {
return false
}
guard let data = value.data(using: .utf8) else { return false }
return set(data, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

/// Save an NSCoding compliant object to the keychain associated with a specified key. If an object already exists for the given key, the object will be overwritten with the new value.
Expand All @@ -293,9 +268,11 @@ open class KeychainWrapper {
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: NSCoding, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: value)

@discardableResult open func set<T>(_ value: T, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool where T : NSSecureCoding {
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else {
return false
}

return set(data, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

Expand All @@ -318,7 +295,7 @@ open class KeychainWrapper {
keychainQueryDictionary[SecAttrAccessible] = KeychainItemAccessibility.whenUnlocked.keychainAttrValue
}

let status: OSStatus = SecItemAdd(keychainQueryDictionary as CFDictionary, nil)
let status = SecItemAdd(keychainQueryDictionary as CFDictionary, nil)

if status == errSecSuccess {
return true
Expand All @@ -331,7 +308,7 @@ open class KeychainWrapper {

@available(*, deprecated, message: "remove is deprecated since version 2.2.1, use removeObject instead")
@discardableResult open func remove(key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return removeObject(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
removeObject(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}

/// Remove an object associated with a specified key. If re-using a key but with a different accessibility, first remove the previous key value using removeObjectForKey(:withAccessibility) using the same accessibilty it was saved with.
Expand All @@ -344,13 +321,8 @@ open class KeychainWrapper {
let keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)

// Delete
let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)

if status == errSecSuccess {
return true
} else {
return false
}
let status = SecItemDelete(keychainQueryDictionary as CFDictionary)
return status == errSecSuccess
}

/// Remove all keychain data added through KeychainWrapper. This will only delete items matching the currnt ServiceName and AccessGroup if one is set.
Expand All @@ -366,13 +338,8 @@ open class KeychainWrapper {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}

let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)

if status == errSecSuccess {
return true
} else {
return false
}
let status = SecItemDelete(keychainQueryDictionary as CFDictionary)
return status == errSecSuccess
}

/// Remove all keychain data, including data not added through keychain wrapper.
Expand All @@ -394,13 +361,8 @@ open class KeychainWrapper {
///
@discardableResult private class func deleteKeychainSecClass(_ secClass: AnyObject) -> Bool {
let query = [SecClass: secClass]
let status: OSStatus = SecItemDelete(query as CFDictionary)

if status == errSecSuccess {
return true
} else {
return false
}
let status = SecItemDelete(query as CFDictionary)
return status == errSecSuccess
}

/// Update existing data associated with a specified key name. The existing data will be overwritten by the new data.
Expand All @@ -414,13 +376,8 @@ open class KeychainWrapper {
}

// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary as CFDictionary, updateDictionary as CFDictionary)

if status == errSecSuccess {
return true
} else {
return false
}
let status = SecItemUpdate(keychainQueryDictionary as CFDictionary, updateDictionary as CFDictionary)
return status == errSecSuccess
}

/// Setup the keychain query dictionary used to access the keychain on iOS for a specified key name. Takes into account the Service Name and Access Group if one is set.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class KeychainWrapperDefaultWrapperTests: XCTestCase {

KeychainWrapper.standard.set(myTestObject, forKey: testKey)

if let retrievedObject = KeychainWrapper.standard.object(forKey: testKey) as? TestObject{
if let retrievedObject = KeychainWrapper.standard.object(forKey: testKey, ofClass: TestObject.self) {
XCTAssertEqual(retrievedObject.objectName, testString, "NSCoding compliant object retrieved for key should have objectName property equal to what it was stored with")
XCTAssertEqual(retrievedObject.objectRating, testInt, "NSCoding compliant object retrieved for key should have objectRating property equal to what it was stored with")
} else {
Expand All @@ -155,7 +155,7 @@ class KeychainWrapperDefaultWrapperTests: XCTestCase {
}

func testNSCodingObjectRetrievalWhenValueDoesNotExist() {
let retrievedObject = KeychainWrapper.standard.object(forKey: testKey) as? TestObject
let retrievedObject = KeychainWrapper.standard.object(forKey: testKey, ofClass: TestObject.self)
XCTAssertNil(retrievedObject, "Object for Key should not exist")
}

Expand Down
2 changes: 0 additions & 2 deletions SwiftKeychainWrapperTests/KeychainWrapperTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ class KeychainWrapperTests: XCTestCase {
let accessibilityOptions: [KeychainItemAccessibility] = [
.afterFirstUnlock,
.afterFirstUnlockThisDeviceOnly,
.always,
.whenPasscodeSetThisDeviceOnly,
.alwaysThisDeviceOnly,
.whenUnlocked,
.whenUnlockedThisDeviceOnly
]
Expand Down
5 changes: 4 additions & 1 deletion SwiftKeychainWrapperTests/TestObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,15 @@

import Foundation

class TestObject: NSObject, NSCoding {
class TestObject: NSObject, NSSecureCoding {

var objectName = "Name"
var objectRating = 0

override init() { }

static var supportsSecureCoding: Bool { true }

required init?(coder decoder: NSCoder) {
if let name = decoder.decodeObject(forKey: "objectName") as? String {
self.objectName = name
Expand Down