Unable to encrypt database in swift 3


#1

var db: OpaquePointer? = nil

    let databasePath = Util.getPath("demo.sqlite")
    
    
    
    // first create database file in document directory with empty data
    
    let newDstPath11 = String(format: "%@/Documents/encrypted.sqlite",NSHomeDirectory())
    
    let newFullDestPath = NSURL(fileURLWithPath: newDstPath11)
    let newDstPath = newFullDestPath.path
    let fileManager = FileManager.default
    
    let success = fileManager.createFile(atPath: newDstPath!, contents: nil, attributes: nil)
    print("Success: ", success)
    
    
    // check newly created file exist at path or not
    
    print("File is present or not: ",fileManager.fileExists(atPath: newDstPath!)) // prints true
    
    
    
    // check sqlite3_open function on newly created file path
    
    let databasePath_NewFile = Util.getPath("encrypted.sqlite")
    
    
    if (sqlite3_open(databasePath, &db) == SQLITE_OK) {

// let key = “ganesh”
// let aaa = sqlite3_key(db, key, Int32(strlen(key)) );
// print("AAA: ", aaa)
//
//

        let aStr = String(format: "%@/Documents/encrypted.sqlite",NSHomeDirectory())
        
       
        if sqlite3_exec(db, "ATTACH DATABASE \(aStr) AS encrypted KEY 'ganesh';".cString(using: String.Encoding.utf8), nil, nil, nil) != SQLITE_OK{
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error opening database: \(errmsg)")
        }
        
        
        
        if sqlite3_exec(db, "SELECT sqlcipher_export('encrypted');", nil, nil, nil) != SQLITE_OK {
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error sqlcipher_export: \(errmsg)")
        }
        
        
        // Detach encrypted database

        if sqlite3_exec(db, "DETACH DATABASE encrypted;", nil, nil, nil) != SQLITE_OK {
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("DETACH DATABASE encrypted: \(errmsg)")
        }
        
        sqlite3_close(db);
        
        
    
    }else{
    
        sqlite3_close(db);
        sqlite3_errmsg(db);
        
    }

// here is my output
Success: true
File is present or not: true
2017-11-22 16:25:34.535897+0530 SQLCipherDemo_21nov[3742:1992593] Error opening database: near “/”: syntax error
2017-11-22 16:25:34.551266+0530 SQLCipherDemo_21nov[3742:1992593] Error sqlcipher_export: unknown database encrypted
2017-11-22 16:25:34.551706+0530 SQLCipherDemo_21nov[3742:1992593] DETACH DATABASE encrypted: no such database: encrypted

please tell me what is problem.


#2

Hello @Ganesh_Padole

There are two probable issues here. First, you should not create the file before using ATTACH. In order for a database to be attached it needs to either a) not exist, or b) be a valid database file. Creating an empty file in the file system is not a valid database.

Second, you are missing quotes in your attach statement. You need to quote the database file name since you are using a full path. That is the reason you are getting a syntax error.

Wrap the file name of the database you are attaching in quotes e.g. ATTACH DATABASE '\(aStr)'.


#3

now my encryption code works. But problem in decryption code.

@IBAction func decryptData(_ sender: Any) {

    var db: OpaquePointer? = nil
     var stmt: OpaquePointer? = nil
    var rc: Int32
    
    // decryption code
    
   let databasePath_NewFile = Util.getPath("demo.sqlite")
    
    let newDstPath11 = String(format: "%@/Documents/encrypted1.sqlite",NSHomeDirectory())
    
    let newFullDestPath = NSURL(fileURLWithPath: newDstPath11)
    let newDstPath = newFullDestPath.path
    
    
    
    // first open encrypted database
    if (sqlite3_open(newDstPath11, &db) == SQLITE_OK) {
        
        print("Database open successfully.")
       
        let result = sqlite3_exec(db, "PRAGMA key = 'ganesh';", nil, nil, nil);
        print("Result: ", result)
        
        
        rc = sqlite3_prepare(db, "PRAGMA cipher_version;", -1, &stmt, nil)
        if (rc != SQLITE_OK) {
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error preparing SQL: \(errmsg)")
        }
        
        
        /*
         sqlite> PRAGMA key = 'testkey';
         sqlite> ATTACH DATABASE 'plaintext.db' AS plaintext KEY '';  -- empty key will disable encryption
         sqlite> SELECT sqlcipher_export('plaintext');
         sqlite> DETACH DATABASE plaintext;
         */
        
        
        let newQuery1 = "ATTACH DATABASE '\(newDstPath11)' AS plaintext KEY '';"
        print("NewQuery: ", newQuery1)
        
        if sqlite3_exec(db, newQuery1, nil, nil, nil) == SQLITE_OK {
            
            if sqlite3_exec(db, "SELECT sqlcipher_export('plaintext');", nil, nil, nil) == SQLITE_OK{
                
                
                if sqlite3_exec(db, "DETACH DATABASE plaintext;", nil, nil, nil) == SQLITE_OK{
                    
                    print("Everything ok:")
                    
                    
                }else{
                    
                    
                    let errmsg = String(cString: sqlite3_errmsg(db))
                    NSLog("DETACH DATABASE encrypted: \(errmsg)")
                }
                
                
            }else{
                let errmsg = String(cString: sqlite3_errmsg(db))
                NSLog("Error sqlcipher_export: \(errmsg)")
            }
            
        }else{
            
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error opening database: \(errmsg)")
            
        }
        
    }
    
    
    
}

////// Here is result

Database open successfully.
Result: 0
NewQuery: ATTACH DATABASE ‘/var/mobile/Containers/Data/Application/9D4EA875-1F99-4642-AFC3-DE5E69F4B47D/Documents/encrypted1.sqlite’ AS plaintext KEY ‘’;
2017-11-28 10:15:34.029860+0530 SQLCipherDemo_21nov[4365:2318614] Error opening database: file is encrypted or is not a database


#4

Actually my task is create new encrypted database file decrypt that encrypted database file .
i am creating encrypted database file in document directory and using same encrypted database file from document directory to decrypt that file , but it is not working.please help me.


#5

@Ganesh_Padole

I’ve responded to your query in your other post Unable to decrypt encrypted database in swift 3