Skip to content

Instantly share code, notes, and snippets.

@thinkclay
Last active August 30, 2016 12:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkclay/6552cffb7780176de62e to your computer and use it in GitHub Desktop.
Save thinkclay/6552cffb7780176de62e to your computer and use it in GitHub Desktop.
Dead simple keychain access
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
}
}
@andrewroycarter
Copy link

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 :)

@kanedo
Copy link

kanedo commented Aug 30, 2016

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