Changing Database Encryption Key

To change database encryption key, create the HHFWRekeyBase application that uses the framework methods:

Method name Brief description
initWithCredentials (_: host: environment: project: device:) The method initializes the framework.
auth (_: password:) The method authenticates the user by login and password.
openBase (_: key:) The method opens connection with database at the specified path.
closeBase (_:) The method closes database connection.
rekeyBase (_: newKey:) The method changes database encryption key at the specified path.

Auxiliary method:

Method name Brief description
getURL (for:) The method returns URL for the file with the specified name in the Documents folder.
Type of returned data: URL.

The HHFWRekeyBase application includes a screen, the UITextView text view, the UITextField text box, and the UIButton buttons:

NOTE. When the application is initialized, authentication is executed, the buttons and the text box are not available. If the authentication is executed successfully, the buttons and the text box are available, and the text view displays the text "Authentication and resources load success".

To execute the example:

  1. Enter the primary database encryption key to the text box and click the Open Database button.

Clicking the button opens a connection or creates a database with the specified primary key. The text view describes the method execution result.

  1. Enter the new database encryption key to the text box and click Rekey Database button.

Clicking the button changes database encryption key. The text view describes the method execution result.

  1. Enter the primary database encryption key to the text box and click the Open Database button.

Clicking the button closes the previous database connection and attempts to open a new connection with the primary key. The text view describes the method execution result.

  1. Enter the new database encryption key specified in Step 2 and click the Open Database button.

Clicking the button closes the previous database connection and attempts to open a new connection with the new key. The text view describes the method execution result.

Application code:

import UIKit
 
class ViewController: UIViewController {
 
    // Declare user interface elements
    @IBOutlet weak var keyTextField: UITextField!
    @IBOutlet weak var openDatabaseButton: UIButton!
    @IBOutlet weak var rekeyDatabaseButton: UIButton!
    @IBOutlet weak var resultTextView: UITextView!
 
    // Execute methods of user interface display cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.deactivateViews()
        self.initializeFramework()
        self.auth {
            self.activateViews()
            self.resultTextView.text = "Authentication success"
        }
    }
 
    // Set methods to handle events initialized by the user from user interface
    @IBAction func openDatabasePressed(_ sender: UIButton) {
        let databaseName = "database.sqlite"
        self.closeDatabase(databaseName)
        let key = self.keyTextField.text ?? ""
        self.resultTextView.text = "Open base with key \"\(key)\" success: \(self.openDatabase(databaseName, key: key))"
    }
    @IBAction func rekeyDatabasePressed(_ sender: UIButton) {
        let databaseName = "database.sqlite"
        let newKey = self.keyTextField.text ?? ""
        self.resultTextView.text = "Rekey base with new key \"\(newKey)\" success: \(self.rekeyDatabase(databaseName, newKey: newKey))"
    }
 
    // Initialize framework
    private func initializeFramework() {
        let apiVersion: String = "v1"
        let host: String = "http://testmasterfmp.fsight.cloud/"
        let environment: String = "DocumentationExampleEnv"
        let project: String = "DocumentationExampleProj"
        let device: String = (UIDevice.current.identifierForVendor?.uuidString)!
        HHFWController.sharedInstance().initWithCredentials(
            apiVersion,
            host: host,
            environment: environment,
            project: project,
            device: device
        )
    }
 
    // Authenticate
    private func auth(completion: @escaping ()->()) {
        let username: String = "test"
        let password: String = "test123"
        HHFWController.sharedInstance().auth(username, password: password){ (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Auth success")
                completion()
            } else {
                print("Auth error")
            }
        }
    }
 
    // Open or create a database
    private func openDatabase(_ databaseName: String, key: String) -> Bool {
        let fullDatabaseURL = self.getURL(for: databaseName)
        return HHFWController.sharedInstance().openBase(fullDatabaseURL.path, key: key)
    }
 
    // Change database encryption key
    private func rekeyDatabase(_ databaseName: String, newKey: String) -> Bool {
        let fullDatabaseURL = self.getURL(for: databaseName)
        return HHFWController.sharedInstance().rekeyBase(fullDatabaseURL.path, newKey: newKey)
    }
 
    // Close database
    private func closeDatabase(_ databaseName: String) -> Bool {
        let fullDatabaseURL = self.getURL(for: databaseName)
        return HHFWController.sharedInstance().closeBase(fullDatabaseURL.path)
    }
 
    // Execute auxiliary methods
    private func getURL(for fileName: String) -> URL {
        let paths: [URL] = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let fileURL: URL = paths[0].appendingPathComponent(fileName)
        return fileURL
    }
 
    // Set methods for changing user interface display elements
    private func deactivateViews() {
        self.keyTextField.isEnabled = false
        self.openDatabaseButton.isEnabled = false
        self.rekeyDatabaseButton.isEnabled = false
    }
    private func activateViews() {
        self.keyTextField.isEnabled = true
        self.openDatabaseButton.isEnabled = true
        self.rekeyDatabaseButton.isEnabled = true
    }
}

See also:

Examples of iOS Framework Use | Examples of Working with Resources