# Unable to encrypt database in swift 3

**URL:** <https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495>\
**Category:** SQLCipher\
**Created:** [November 22, 2017, 10:57am UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495 "2017-11-22T10:57:12Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ganesh\_Padole](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@Ganesh\_Padole](https://discuss.zetetic.net/u/Ganesh_Padole)\
**Post date:** [November 22, 2017, 10:57am UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495/1 "2017-11-22T10:57:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![sjlombardo](https://sea2.discourse-cdn.com/flex016/user_avatar/discuss.zetetic.net/sjlombardo/32/3_2.png) [@sjlombardo](https://discuss.zetetic.net/u/sjlombardo)\
**Post date:** [November 27, 2017, 3:42pm UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495/2 "2017-11-27T15:42:54Z")

</div>

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.

> [@Ganesh\_Padole](#):
>
> ```
> let success = fileManager.createFile(atPath: newDstPath!, contents: nil, attributes: nil)
> print("Success: ", success)
> 
> ```

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.

> [@Ganesh\_Padole](#):
>
> 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)”)  
> }

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

---

<div class="post-metadata">

**Author:** ![Ganesh\_Padole](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@Ganesh\_Padole](https://discuss.zetetic.net/u/Ganesh_Padole)\
**Post date:** [November 28, 2017, 4:48am UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495/3 "2017-11-28T04:48:55Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Ganesh\_Padole](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@Ganesh\_Padole](https://discuss.zetetic.net/u/Ganesh_Padole)\
**Post date:** [November 29, 2017, 1:42pm UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495/4 "2017-11-29T13:42:00Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![mmoore](https://sea2.discourse-cdn.com/flex016/user_avatar/discuss.zetetic.net/mmoore/32/858_2.png) [@mmoore](https://discuss.zetetic.net/u/mmoore)\
**Post date:** [November 29, 2017, 3:00pm UTC](https://discuss.zetetic.net/t/unable-to-encrypt-database-in-swift-3/2495/5 "2017-11-29T15:00:47Z")

</div>

@Ganesh_Padole

I’ve responded to your query in your other post [Unable to decrypt encrypted database in swift 3](https://discuss.zetetic.net/t/unable-to-decrypt-encrypted-database-in-swift-3/2509/5)
