Building an Okta Clone (Part 3): Storing in the Keychain

With the app now displaying the core components, we need to tighten things up a little more. Right now we have a hardcoded secret. If the app were to be decompiled then the secret would be exposed and the entire integrity of our app would be compromised. Typically this code would be sent from the server via a QR code, the user would scan it, and that code would be extracted and saved. We are going to generate a test code again, but this time we are going to store it in the keychain ourselves. After we can store it securely in the keychain, then we will take it a step further and generate a QR code. ## Storing in the Keychain The Keychain API is fairly old. It still uses C libraries and can be a pain. In most cases we would simply use a wrapper like Valet or KeychainSwift to do this for us. To help us understand what is actually happening here though, we are going to make our own wrapper called KeychainManager. Here is a basic outline of what its going to look like in KeychainManager.swift: import Security struct KeychainManager { // We identify our keys by an "Account Name" (like a dictionary key) static let account = "com.oktaclone.totp.secret" enum KeychainError: Error { case duplicateEntry case unknown(OSStatus) case itemNotFound } // TODO: Implement Save static func save(key: Data) throws { // 1. Prepare the Query // 2. Call SecItemAdd } // TODO: Implement Read static func read() throws -> Data { // 1. Prepare the Query // 2. Call SecItemCopyMatching return Data() } } We have our basic error types and a function for saving and reading. ## Saving the Data To save something to the Keychain, we create a "Query" (a dictionary) that describes the item. We need to define 4 things: * Class: What is it? (kSecClassGenericPassword) * Account: What is its ID? (Our string constant for account) * Value: The actual data. * Accessibility: When can we read it? (kSecAttrAccessibleWhenUnlocked - This ensures the data is encrypted until the user unlocks their phone). After we have those 4 values, we need to then delete any existing items to avoid duplicates, Add it as a secure item, then handle any errors we might get from trying to add it: static func save(key: Data) throws { // 1. Construct the Query // We cast Swift strings/data to CoreFoundation types (CFString, CFData) implicitly let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: account, kSecValueData as String: key, // "WhenUnlocked" encrypts the item on disk using the device passcode kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked ] // 2. Delete Existing Items to Avoid Duplicates SecItemDelete(query as CFDictionary) // 3. Add the Item let status = SecItemAdd(query as CFDictionary, nil) // 4. Handle Errors guard status == errSecSuccess else { throw KeychainError.unknown(status) } } ## Reading the Data Reading is slightly different. We provide the same query (Class + Account), but instead of providing data, we ask for it back (kSecReturnData = true). After we make our query, we are also going to need a temporary variable to hold a reference to the result. After accounting for potential errors, we can then return the data: static func read() throws -> Data { // 1. Construct the Query let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: account, kSecMatchLimit as String: kSecMatchLimitOne, // We only want one result kSecReturnData as String: true // Please return the binary data ] // 2. Execute the Copy Command // We need a temporary variable to hold the result reference var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) // 3. Handle Results guard status != errSecItemNotFound else { throw KeychainError.itemNotFound } guard status == errSecSuccess else { throw KeychainError.unknown(status) } // 4. Cast and Return guard let data = item as? Data else { throw KeychainError.unknown(status) } return data } ## Implementing the Manager Now that the Keychain Manager is ready to go, lets implement it into the view model. First thig we need to do is find the secret variable and replace it with an empty one: private var secret: Data? Next we are going to make our load function and call it in the initializer. The load function will try to read the key from the keychain. If that doesn’t work it will generate a simple key (which we will tackle in the next one). After it generates the key, it will save it to the keychain: init() { loadSecret() startTimer() } func loadSecret() { do { // Try to read from Keychain self.secret = try KeychainManager.read() print("Success: Loaded secret from Keychain") } catch { print("Keychain Empty or Error: \(error)") // For testing only: Generate a random key and save it // In the real app, this will come from the QR Code let testSecret = Data("12345678901234567890".utf8) try? KeychainManager.save(key: testSecret) self.secret = testSecret print("Saved new test secret to Keychain") } } Now the last thing to do is to make sure we guard against a missing key in the update function: private func update() { // Guard against missing secret guard let secret = secret else { return } … } You should be all set and the key should be saving (if there isn’t one), but you should mostly be seeing: “Success: Loaded secret from keychain” If you are not and want to test this by manually deleting a key and making sure that it generates a new key, we can add the delete function to the keychain manager: static func delete() throws { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: account ] let status = SecItemDelete(query as CFDictionary) // It's okay if the item isn't found (errSecItemNotFound), that counts as a success guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError.unknown(status) } print("Keychain data wiped.") } Then we can call it in the initializer of our view model, but remember to comment it back out again! init() { // UNCOMMENT THIS LINE, RUN ONCE, THEN COMMENT IT OUT AGAIN // try? KeychainManager.delete() loadSecret() startTimer() } Now with all of that, we should be set to start implementing the QR code, which we’ll take a look at in the next one.