我使用sqlciper与android加密现有的sqlite数据库,并遇到加密数据库不包含我的表的问题,它只包含sqlite_master和android_metadata.
我原来的db看起来像:
shell@umts_spyder:/sdcard $sqlite3 d000000.dat
sqlite3 d000000.dat
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from sqlite_master;
select * from sqlite_master;
table|android_metadata|android_metadata|2|CREATE TABLE android_metadata (locale TEXT)
table|PageData|PageData|3|CREATE TABLE PageData(File_Path TEXT NOT NULL UNIQUE, File_Content BLOB)
index|sqlite_autoindex_PageData_1|PageData|4|
我在下面粘贴我的加密代码,使用空键(“”)打开普通数据库,如果使用null,则引发NullPointerException(对于我在帖子末尾提到的两个普通数据库):
File plain = new File(mDbPath); /* /sdcard/d0000000.dat */
File encrypt = new File(plain.getParent(), "encrypted.dat");
encrypt.delete();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mDbPath, "", null);
String sql = String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypt.getPath(), mvKey.getText().toString()); // key is qqqqqqqq
db.execSQL(sql);
db.rawQuery("SELECT sqlcipher_export('encrypted')", null);
db.execSQL("DETACH DATABASE encrypted");
以下是我用来测试加密数据库的代码,输出中只有“android_metadata”,我的表PageData丢失了.如果我直接使用“select * from PageData”,它不会引发这样的表异常:
File file = new File(Environment.getExternalStorageDirectory(), "encrypted.dat");
if(!file.exists())
{
mvBrowse.setText("not exist");
return;
}
String key = mvKey.getText().toString();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, key, null);
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master", null);
String str = new String();
while(cursor.moveToNext())
{
str += cursor.getString(1)+", ";
}
mvBrowse.setText(str); // output is "android_metadata, "
cursor.close();
db.close();
加密应该工作,因为如果我用empty(“”)键打开encrypted.dat,它会引发“文件加密或不是数据库”异常,但我可以用正确的密钥读取sqlite_master和android_metadata表.
我确认我测试的路径与我编写的加密路径相同;
使用空键测试由sqlcipher创建普通数据库:
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, "", null); /* /sdcard/d000000.dat */
db.execSQL("CREATE TABLE PageData(File_Path TEXT NOT NULL UNIQUE, File_Content BLOB)");
以及通过标准的sqlite工具创建它(SQLite Export Professional,在这种情况下我没有使用BLOB字段,只有TEXT和INTEGER);
并测试了两个API版本,“SQLCipher for Android v2.2.2”和“SQLCipher for Android v3.0.0”.
以上都得到了相同的结果.有人会帮助我吗?我相信里面有一些小错,但我无法弄明白.
解决方法:
String sql = String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypt.getPath(), mvKey.getText().toString());
db.rawExecSQL(sql);
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted");
标签:android,sqlite,encryption
来源: https://codeday.me/bug/20190825/1717386.html