Last active
August 30, 2016 12:13
-
-
Save thinkclay/6552cffb7780176de62e to your computer and use it in GitHub Desktop.
Dead simple keychain access
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Security | |
public class Keychain | |
{ | |
public class func set(key: String, value: String) -> Bool | |
{ | |
if let data = value.dataUsingEncoding(NSUTF8StringEncoding) | |
{ | |
return set(key, value: data) | |
} | |
return false | |
} | |
public class func set(key: String, value: NSData) -> Bool | |
{ | |
let query = [ | |
(kSecClass as! String) : kSecClassGenericPassword, | |
(kSecAttrAccount as! String) : key, | |
(kSecValueData as! String) : value | |
] | |
SecItemDelete(query as CFDictionaryRef) | |
return SecItemAdd(query as CFDictionaryRef, nil) == noErr | |
} | |
public class func get(key: String) -> NSString? | |
{ | |
if let data = getData(key) | |
{ | |
return NSString(data: data, encoding: NSUTF8StringEncoding) | |
} | |
return nil | |
} | |
public class func getData(key: String) -> NSData? | |
{ | |
let query = [ | |
(kSecClass as! String) : kSecClassGenericPassword, | |
(kSecAttrAccount as! String) : key, | |
(kSecReturnData as! String) : kCFBooleanTrue, | |
(kSecMatchLimit as! String) : kSecMatchLimitOne | |
] | |
var dataTypeRef: Unmanaged<AnyObject>? | |
let status = SecItemCopyMatching(query, &dataTypeRef) | |
if status == noErr && dataTypeRef != nil | |
{ | |
return dataTypeRef!.takeRetainedValue() as? NSData | |
} | |
return nil | |
} | |
public class func delete(key: String) -> Bool | |
{ | |
let query = [ | |
(kSecClass as! String) : kSecClassGenericPassword, | |
(kSecAttrAccount as! String) : key | |
] | |
return SecItemDelete(query as CFDictionaryRef) == noErr | |
} | |
public class func clear() -> Bool | |
{ | |
let query = [ | |
(kSecClass as String): kSecClassGenericPassword | |
] | |
return SecItemDelete(query as CFDictionaryRef) == noErr | |
} | |
} |
I forked your code and fixed some changes to make it work with Swift 2.2 and Xcode 7.3.1
You can find the adapted code there:
https://github.com/kanedo/Keychain
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you post a license for this? I'd love to use a somewhat altered version in my app but am hesitant without a clear license! Thanks for putting this out here, the keychain API is certainly not a joy to work with :)