In-memory encryption not working

I created one In-memory database and I tried to encrypt and serialize the database by using sqlite3_serialize() the in-memory database, but the output of sqlite3_serialize() is a nonencrypted database.

my code:

sqlite3* db;
char* ErrMsg;
int status = sqlite3_open(":memory:", &db);

if (sqlite3_exec(db, "PRAGMA key = 'KEY';", 0, NULL, &ErrMsg) == SQLITE_OK)

if (sqlite3_exec(db, "PRAGMA cipher_hmac_algorithm = HMAC_SHA1;", 0, NULL, &ErrMsg) == SQLITE_OK)

if (sqlite3_exec(db, "PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA1;", 0, NULL, &ErrMsg) == SQLITE_OK)


if (status == SQLITE_OK)
	int exit = 0;

	char* messaggeError = NULL;

	std::string sql = "CREATE TABLE PERSON("
		"NAME           TEXT    NOT NULL, "
		"SURNAME          TEXT     NOT NULL, "
		"AGE            INT     NOT NULL, "
		"ADDRESS        CHAR(50), "
		"SALARY         REAL );";

	exit = sqlite3_exec(db, sql.c_str(), NULL, NULL, &messaggeError);

	std::string insert_query("INSERT INTO PERSON VALUES(1, 'STEVE', 'GATES', 30, 'PALO ALTO', 1000.0);"
		"INSERT INTO PERSON VALUES(3, 'PAUL', 'JOBS', 24, 'SEATTLE', 9900.0);");

	exit = sqlite3_exec(db, insert_query.c_str(), NULL, NULL, &messaggeError);	
	sqlite3_int64 serilized_count;
	unsigned char* serialized_output = sqlite3_serialize(db,0, &serilized_count,0);

The output of the sqlite3_serialize() is non encrypted db;

Hi @pradeep

One solution that will work for your scenario is to attach a database with a specified key, then calling sqlcipher_export(...). Would you give that a try and let us know your results?

Thanks for your response
I am new to sqlite kindly provide example based on my code.

Hi @pradeep

Please review the documentation for sqlcipher_export(...), specifically example #1. Those commands can be executed using sqlite3_exec as well.

I need to encyrpt inmemory db without creating any physical file,it is possible?

For further context, it is not possible to use sqlite3_serialize() to get access to encrypted data. sqlite3_serialize() creates a representation of the database after it is retrieved through paging system. Therefore, even if the underlying database is encrypted the serialized version of the database will be plaintext in the allocated memory segment returned from the function. You will observe the same behavior even when using an encrypted database file (i.e. when serialized, the resulting memory buffer will be plaintext, even if the file is encrypted on disk).

@pradeep - No, that is not a feature that SQLCipher supports at this time.

There is any other way to backup encrypted in-memory database without physical file.

Hello @pradeep - no, there isn’t really any way to do that with SQLCipher. You could sqlite3_serialize() into a block of memory and then encrypt it yourself, but SQLCipher will not it for you.

Thanks for you reply.