Replace ATTACH, SELECT, DETACH with sqlite3_key and sqlite3_rekey

Hi, I i am using below APIs to create and encrypt sql DB:

sqlite3_open(/tmp/myDB, &db);
sprintf(sqlQuery,%s, “ATTACH DATABASE ‘/tmp/encrypted.db’ AS encrypted KEY ‘abcd’”);
sqlite3_exec(db, sqlQuery, NULL, NULL, NULL);
sqlite3_exec(db, “SELECT sqlcipher_export(‘encrypted’);”, NULL, NULL, NULL);
sqlite3_exec(persistence_db,“DETACH DATABASE encrypted;”,NULL, NULL, NULL);
system(“mv /tmp/encrypted.db /tmp/myDB”);

Instead of this, can I use below APIs to encrypt db?

sqlite3_open(/tmp/myDB, &db);
sqlite3_key(db, “abcd”, strlen(“abcd”)) ;
sqlite3_rekey(db, “abcd”, strlen(“abcd”)) ;

@pdp - no, you can’t use sqlite3_rekey to encrypt a standard (plaintext) SQLite database. The only supported way to do that is via ATTACH and sqlcipher_export(). See here for more details:

Thanks Sjlombardo for reply. As per information given in post sqlite3_key and PRAGMA key can only be used when opening a brand new database. In my case I was calling sqlite3_key only for 1st time at the time of creation. But what I observed is that I need to use both sqlite3_key and sqlite3_rekey to encrypt DB. Only sqlite3_key alone is not enough.

Hello @pdp - that is definitely not the case. Using sqlite3_key as the first operation on a brand new database after it is opened will cause the database to be encrypted. If you are seeing otherwise there may be some issue with your application or the integration. Can you create an isolate standalone example?