Sqlcipher backend
- Although this extention’s code is short, it has not been properly peer-reviewed yet and may have introduced vulnerabilities.
- The code contains minimum values for passphrase length and kdf_iter, as well as a default value for the later. Do not regard these numbers as advice. Consult the docs at http://sqlcipher.net/sqlcipher-api/ and security experts.
Also note that this code relies on pysqlcipher and sqlcipher, and the code there might have vulnerabilities as well, but since these are widely used crypto modules, we can expect “short zero days” there.
sqlcipher_ext API notes
class SqlCipherDatabase
(database, passphrase, kdf_iter=64000, \*kwargs*)
Subclass of SqliteDatabase
that stores the database encrypted. Instead of the standard sqlite3
backend, it uses pysqlcipher: a python wrapper for sqlcipher, which – in turn – is an encrypted wrapper around sqlite3
, so the API is identical to SqliteDatabase
’s, except for object construction parameters:
Parameters: |
|
---|
- If the
database
file doesn’t exist, it will be created with encryption by a key derived frompasshprase
withkdf_iter
PBKDF2 iterations. When trying to open an existing database,
passhprase
andkdf_iter
should be identical to the ones used when it was created.rekey
(passphrase)Parameters: passphrase (str) – New passphrase for database. Change the passphrase for database.
Notes:
[Hopefully] there’s no way to tell whether the passphrase is wrong or the file is corrupt. In both cases – the first time we try to acces the database – a
DatabaseError
error is raised, with the exact message:"file is encrypted or is not a database"
.As mentioned above, this only happens when you access the databse, so if you need to know right away whether the passphrase was correct, you can trigger this check by calling [e.g.]
get_tables()
(see example below).Most applications can expect failed attempts to open the database (common case: prompting the user for
passphrase
), so the database can’t be hardwired into theMeta
of model classes. To defer initialization, pass None in to the database.
Example:
db = SqlCipherDatabase(None)
class BaseModel(Model):
"""Parent for all app's models"""
class Meta:
# We won't have a valid db until user enters passhrase.
database = db
# Derive our model subclasses
class Person(BaseModel):
name = TextField(primary_key=True)
right_passphrase = False
while not right_passphrase:
db.init(
'testsqlcipher.db',
passphrase=get_passphrase_from_user())
try: # Actually execute a query against the db to test passphrase.
db.get_tables()
except DatabaseError as exc:
# This error indicates the password was wrong.
if exc.args[0] == 'file is encrypted or is not a database':
tell_user_the_passphrase_was_wrong()
db.init(None) # Reset the db.
else:
raise exc
else:
# The password was correct.
right_passphrase = True
See also: a slightly more elaborate example.