Last active
October 2, 2018 17:29
-
-
Save rldaulton/4af40f7113c035e49adf6846b866d42c to your computer and use it in GitHub Desktop.
Saving Sensitive Information to iOS Keychain
This file contains 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
func testPaswordRetrive() { | |
let password = "123456" | |
let account = "User" | |
keyChainService.save(password, for: account) | |
XCTAssertEqual(keyChainService.retrivePassword(for: account), password) | |
} | |
//... | |
class KeychainService { | |
func save(_ password: String, for account: String) { | |
let password = password.data(using: String.Encoding.utf8)! | |
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, | |
kSecAttrAccount as String: account, | |
kSecValueData as String: password] | |
let status = SecItemAdd(query as CFDictionary, nil) | |
guard status == errSecSuccess else { return print("save error") | |
} | |
func retrivePassword(for account: String) -> String? { | |
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, | |
kSecAttrAccount as String: account, | |
kSecMatchLimit as String: kSecMatchLimitOne, | |
kSecReturnData as String: kCFBooleanTrue] | |
var retrivedData: AnyObject? = nil | |
let _ = SecItemCopyMatching(query as CFDictionary, &retrivedData) | |
guard let data = retrivedData as? Data else {return nil} | |
return String(data: data, encoding: String.Encoding.utf8) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Optionally, save a hashed version of your sensitive information using CryptoSwift