How to encrypt and decrypt using 'FMDB/SQLCipher' in Swift?
Asked Answered
H

1

17

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.

Heretical answered 21/9, 2016 at 16:47 Comment(2)
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: discuss.zetetic.net/t/… I don't know fmdb, so I'm not able to provide any API-level guidance for this operation.Grouch
Can you tell, how you have added FMDB framework? I think i might help.Hallel
M
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
}
Malherbe answered 18/7, 2020 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.