Skip to content

Instantly share code, notes, and snippets.

@rldaulton
Last active October 2, 2018 17:29
Show Gist options
  • Save rldaulton/4af40f7113c035e49adf6846b866d42c to your computer and use it in GitHub Desktop.
Save rldaulton/4af40f7113c035e49adf6846b866d42c to your computer and use it in GitHub Desktop.
Saving Sensitive Information to iOS Keychain
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)
}
}
@rldaulton
Copy link
Author

Optionally, save a hashed version of your sensitive information using CryptoSwift

func saveEncryptedPassword(_ password: String, for account: String) {
    let salt = Array("salty".utf8)
    let key = try! HKDF(password: Array(password.utf8), salt: salt, variant: .sha256).calculate().toHexString()
    keychainService.save(key, for: account)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment