m4heshd / better-sqlite3-multiple-ciphers

better-sqlite3 with multiple-cipher encryption support 🔒
MIT License
140 stars 27 forks source link

Reading an encrypted file into buffer before creating database #42

Closed protex closed 1 year ago

protex commented 1 year ago

I've got an interesting situation where I have a "database" where the first 1024 bytes are used as a header for an application. So, the actual database starts at byte 1025. I would like to be able to load the database via a buffer so that I remove the extra bytes in memory before actually creating the Database instance, but I'm not sure how to do this.

I've manually removed the first 1024 bytes and verified that the database works correctly by doing this:

var Database = require('better-sqlite3-multiple-ciphers')
var db = new Database('vault.db');

db.pragma("cipher='sqlcipher'")
db.pragma(`legacy=3`)
db.pragma(`key = "x'<my-hex-key>'"`);

x = db.prepare("select name from sqlite_master where type='table' and name='item'").all()

console.log(x)

db.close();

I get the expected return of [ { name = "item" } ].

I then try the following (load file into buffer, pass buffer into Database)

var fs = require('fs');
var Database = require('better-sqlite3-multiple-ciphers')

var buf = fs.readFileSync('vault.db')
var db = new Database(buf);

db.pragma("cipher='sqlcipher'")
db.pragma(`legacy=3`)
db.pragma(`key = "x'<my-hex-key>'"`);

x = db.prepare("select name from sqlite_master where type='table' and name='item'").all()

console.log(x)

db.close();

I would have expected this to work properly, but instead I end up with an SQLITE_NOTADB error. Is there something special I need to do to that buffer to get this to work?

m4heshd commented 1 year ago

Hi @protex,

That's because a buffer is practically an in-memory database, and as documented here, in-memory databases neither support encryption nor decryption.

SQLite’s Virtual File System encryption can be supported only for ordinary file based databases, not for memory based databases

Closing the issue since this is expected behavior.