15

I have used FMDB to create a SQLite database in Swift. But now I want to encrypt it. So can anyone please help me with the Swift version of encrypting and decrypting SQLite database using 'FMDB/SQLCipher'? I was not able to find a good tutorial to understand this.

Nuthan
  • 151
  • 4
  • You'll need to open the plaintext database and copy it to an encrypted one, then delete the plaintext one, as described in the SQLCipher docs: https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868 I don't know fmdb, so I'm not able to provide any API-level guidance for this operation. – Palpatim Dec 22 '16 at 15:26
  • Can you tell, how you have added FMDB framework? I think i might help. – Saurabh Yadav Dec 25 '16 at 19:53

1 Answers1

0

Below is a sample code that sets a key on a database which is a FMDatabase object. You have to use the setKey() method in order to access an encrypted database. I have also written a wrapper over FMDB library which will make your life easier dealing with encrypted databases.

Here it is : https://github.com/SagarSDagdu/SDDatabase/ It also has ample amount of documentation and example code.

func executeUpdate(onDatabase database:FMDatabase, withStatement statement:String, values: [Any]?) -> Bool {
    var success:Bool = false
    do {
        database.logsErrors = self.loggingEnabled
        if let key = self.dbPassKey { //Use your key here
            database.setKey(key)
        }
        try database.executeUpdate(statement, values:values)
        success = true
    }
    catch {
        print("Error in \(#function) with query: \(statement), error : \(error)")
    }
    return success
}
Sagar D
  • 2,588
  • 1
  • 18
  • 31