Sqlcipher backend
- Although this extention’s code is short, it has not been properlypeer-reviewed yet and may have introduced vulnerabilities.
Also note that this code relies on pysqlcipher and sqlcipher, andthe code there might have vulnerabilities as well, but since theseare widely used crypto modules, we can expect “short zero days” there.
sqlcipher_ext API notes
- class
SqlCipherDatabase
(database, passphrase, **kwargs) - Subclass of
SqliteDatabase
that stores the databaseencrypted. Instead of the standardsqlite3
backend, it uses pysqlcipher:a python wrapper for sqlcipher, which – in turn – is an encrypted wrapperaroundsqlite3
, so the API is identical toSqliteDatabase
’s,except for object construction parameters:
Parameters:
- database – Path to encrypted database filename to open [or create].
- passphrase – Database encryption passphrase: should be at least 8 characterlong, but it is strongly advised to enforce better passphrase strengthcriteria in your implementation.
- If the
database
file doesn’t exist, it will be created withencryption by a key derived frompasshprase
. - When trying to open an existing database,
passhprase
should beidentical to the ones used when it was created. If the passphrase isincorrect, an error will be raised when first attempting to access thedatabase. rekey
(passphrase)
Parameters:passphrase (str) – New passphrase for database.
Change the passphrase for database.
Note
SQLCipher can be configured using a number of extension PRAGMAs. The listof PRAGMAs and their descriptions can be found in the SQLCipher documentation.
For example to specify the number of PBKDF2 iterations for the keyderivation (64K in SQLCipher 3.x, 256K in SQLCipher 4.x by default):
- # Use 1,000,000 iterations.
- db = SqlCipherDatabase('my_app.db', pragmas={'kdf_iter': 1000000})
To use a cipher page-size of 16KB and a cache-size of 10,000 pages:
- db = SqlCipherDatabase('my_app.db', passphrase='secret!!!', pragmas={
- 'cipher_page_size': 1024 * 16,
- 'cache_size': 10000}) # 10,000 16KB pages, or 160MB.
Example of prompting the user for a passphrase:
- 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.