Encrypt database


#1

Hello Guys,

when we encrypt database, we use “ATTACH DATABASE ‘OurDBName’ AS encrypted KEY ‘password’”, currently the password is plain text in the SQL statement, is there any alternative solution that we don’t have to put the password in the SQL statement or other API we can use in order to encrypt database?

Thanks


#2

Hi Albert,

Take a look at the SQLite bind parameters reference:

https://www.sqlite.org/c3ref/bind_blob.html

Here’s an example in Objective-C:

NSString *password = ...;
NSString *sql = @"ATTACH DATABASE 'OurDBName' AS encrypted KEY ?;";
if (sqlite3_prepare_v2(database, [sqlCommand UTF8String], -1, &stmt, NULL) == SQLITE_OK) {
	// Starting index for left-most param is 1, not 0
	sqlite3_bind_text(stmt, 1, [password UTF8String], -1, SQLITE_TRANSIENT);
	int rc = sqlite3_step(stmt);
}

Does that help? When opening a database, as opposed to doing an ATTACH, you can use sqlite3_key() instead of composing SQL with your password and PRAGMA key.


#3

Thanks for the quick reply, is there any way to do the similar thing in Java?


#4

Hello @AlbertWangCa by Java, are you referring to Android? If so, yes, you can do parameter binding via the SQLCipher Android API in the same way using execSQL. You will find that it, and other methods (query, rawQuery, etc) take a selectionArgs, array that maps to binding parameters (?). Here is an example of using it with ATTACH:


#5

Awesome, thanks so much sjlombardo