setPassword static method
Sets the password of the database, if any, which has to happen
before any other statement accesses it.
SQLite builds without encryption ignore the password, so they are rejected instead of storing the database unencrypted.
Implementation
static Future<void> setPassword(
final Database database,
final String? password,
) async {
if (password != null) {
validatePassword(password);
// SQLite builds without encryption, e.g. on the web, ignore it
await database
.execute("PRAGMA key = '${password.replaceAll("'", "''")}'");
// SQLite3MultipleCiphers reports its cipher, SQLCipher its version
if ((await database.rawQuery('PRAGMA cipher')).isEmpty &&
(await database.rawQuery('PRAGMA cipher_version')).isEmpty) {
throw DatabaseEncryptionException(
"The SQLite library doesn't support encryption, so the database "
'would be stored unencrypted. Use an encrypted build of SQLite, '
'e.g. with `hooks: user_defines: sqlite3: source: sqlite3mc` in the '
'pubspec.yaml.',
);
}
}
// reading fails if the password doesn't decrypt the database
try {
await database.rawQuery('SELECT count(*) FROM sqlite_master');
} on DatabaseException catch (exception, stackTrace) {
if (exception.getResultCode() != _notADatabase) rethrow;
Error.throwWithStackTrace(
DatabaseEncryptionException(
password == null
? "The database can't be read without password, so it's "
"encrypted or isn't a database."
: "The database can't be decrypted with the password, which is "
"wrong, or the database isn't encrypted.",
exception,
),
stackTrace,
);
}
_passwords[database] = password ?? _noPassword;
}