Created
March 31, 2019 23:56
-
-
Save fcaldarelli/74e1a236421d1f141b3083cdb61447da to your computer and use it in GitHub Desktop.
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
// This two values identify the entry, together they become the | |
// primary key in the database | |
let myAttrService = "app_name" | |
let myAttrAccount = "first_name" | |
// DELETE keychain item (if present from previous run) | |
let delete_query: NSDictionary = [ | |
kSecClass: kSecClassGenericPassword, | |
kSecAttrService: myAttrService, | |
kSecAttrAccount: myAttrAccount, | |
kSecReturnData: false | |
] | |
let delete_status = SecItemDelete(delete_query) | |
if delete_status == errSecSuccess { | |
print("Deleted successfully.") | |
} else if delete_status == errSecItemNotFound { | |
print("Nothing to delete.") | |
} else { | |
print("DELETE Error: \(delete_status).") | |
} | |
// INSERT keychain item | |
let valueData = "The Top Secret Message V1".data(using: .utf8)! | |
let sacObject = | |
SecAccessControlCreateWithFlags(kCFAllocatorDefault, | |
kSecAttrAccessibleWhenUnlockedThisDeviceOnly, | |
.userPresence, | |
nil)! | |
let insert_query: NSDictionary = [ | |
kSecClass: kSecClassGenericPassword, | |
kSecAttrAccessControl: sacObject, | |
kSecValueData: valueData, | |
kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow, | |
kSecAttrService: myAttrService, | |
kSecAttrAccount: myAttrAccount | |
] | |
let insert_status = SecItemAdd(insert_query as CFDictionary, nil) | |
if insert_status == errSecSuccess { | |
print("Inserted successfully.") | |
} else { | |
print("INSERT Error: \(insert_status).") | |
} | |
DispatchQueue.global().async { | |
// RETRIEVE keychain item | |
let select_query: NSDictionary = [ | |
kSecClass: kSecClassGenericPassword, | |
kSecAttrService: myAttrService, | |
kSecAttrAccount: myAttrAccount, | |
kSecReturnData: true, | |
kSecUseOperationPrompt: "Authenticate to access secret message" | |
] | |
var extractedData: CFTypeRef? | |
let select_status = SecItemCopyMatching(select_query, &extractedData) | |
if select_status == errSecSuccess { | |
if let retrievedData = extractedData as? Data, | |
let secretMessage = String(data: retrievedData, encoding: .utf8) { | |
print("Secret message: \(secretMessage)") | |
// UI updates must be dispatched back to the main thread. | |
DispatchQueue.main.async { | |
self.messageLabel.text = secretMessage | |
} | |
} else { | |
print("Invalid data") | |
} | |
} else if select_status == errSecUserCanceled { | |
print("User canceled the operation.") | |
} else { | |
print("SELECT Error: \(select_status).") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment