android sqlcipher判断是否解密成功,在Android中使用SQLCipher加密/解密现有数据库

我正在使用下面的代码来加密和解密我可以加密的数据库,但是当我尝试解密时,我遇到了以下异常.我提到documentation和TestCases仍然仍然面临相同的问题.

例外:

sqlite returned: error code = 26, msg = file is encrypted or is not a database

CREATE TABLE android_metadata failed

Failed to setLocale() when constructing, closing the database

net.sqlcipher.database.SQLiteException: file is encrypted or is not a database

加密:

private static void ConvertNormalToSQLCipheredDB(Context context,

String startingFileName, String endingFileName, String filePassword)

throws IOException {

File mStartingFile = context.getDatabasePath(startingFileName);

if (!mStartingFile.exists()) {

return;

}

File mEndingFile = context.getDatabasePath(endingFileName);

mEndingFile.delete();

SQLiteDatabase database = null;

try {

database = SQLiteDatabase.openOrCreateDatabase(MainApp.mainDBPath,

"", null);

database.rawExecSQL(String.format(

"ATTACH DATABASE '%s' AS encrypted KEY '%s'",

mEndingFile.getAbsolutePath(), filePassword));

database.rawExecSQL("select sqlcipher_export('encrypted')");

database.rawExecSQL("DETACH DATABASE encrypted");

database.close();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (database.isOpen())

database.close();

mStartingFile.delete();

}

}

解密:

private void decryptDatabase() {

File unencryptedFile = getDatabasePath(PhoneNumbersDatabase.DATABASE_NAME);

unencryptedFile.delete();

File databaseFile = getDatabasePath("encrypt.db");

SQLiteDatabaseHook hook = new SQLiteDatabaseHook() {

public void preKey(SQLiteDatabase sqLiteDatabase) {

sqLiteDatabase

.rawExecSQL("PRAGMA cipher_default_use_hmac = off;");

}

public void postKey(SQLiteDatabase sqLiteDatabase) {

}

};

SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(

databaseFile, "test123", null, hook); // Exception

if (database.isOpen()) {

database.rawExecSQL(String.format(

"ATTACH DATABASE '%s' as plaintext KEY '';",

unencryptedFile.getAbsolutePath()));

database.rawExecSQL("SELECT sqlcipher_export('plaintext');");

database.rawExecSQL("DETACH DATABASE plaintext;");

android.database.sqlite.SQLiteDatabase sqlDB = android.database.sqlite.SQLiteDatabase

.openOrCreateDatabase(unencryptedFile, null);

sqlDB.close();

database.close();

}

databaseFile.delete();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值