在SQLite Android中存储和检索加密值

时间:2017-05-24 10:45:00

标签: android sqlite encryption

我有一个EditText e,我正在使用此方法加密其内容的值

byte[] encodeData(byte[] key, byte[] data)
{
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        return cipher.doFinal(data);
    } catch(Exception e) {
        Log.e("Cryptography", e.getMessage());
    }
    return new byte[0];
}

我只是将此方法称为

byte[] encoded = encodeData(key, e.getText.toString());

将值存储在SQLiteDatabse中

SQLiteDatabase sd = db.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("COL_NAME", encoded);

然后使用以下功能

检索它
byte[] decodeData(byte[] key, byte[] data)
{
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        return cipher.doFinal(data);
    } catch(Exception e) {
        Log.e("Cryptography", e.getMessage());
    }
    return new byte[0];
}

并将其称为

SQLiteDatabase sd = db.getReadableDatabase();
Cursor cur = sd.rawQuery("select * from TABLE_NAME", null);
if(cur.moveToNext()) {
    byte[] decoded = decodeData(key, cur.getBlob(0));
}

但是当我将EditText的值设置为此值时,它显示为空白。

e.setText(new String(decoded));

虽然如果我没有加密存储数据,它可以正常工作!

1 个答案:

答案 0 :(得分:-1)

我猜你是以错误的方式处理Cursor。

if (c.moveToFirst()) {
  while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG
    ...
    c.moveToNext();
  } 
}