2017-05-24 23 views
-3

我有一个EditText e,我用这个方法存储和SQLite中检索加密值的Android

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)); 

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

+0

现在读取日志,好像你在做'e.setText(new String(new byte [0]));'...也'cur.getBlob(0)'你确定blob列是第一列? – Selvin

+0

ohh yes ....我在decodeData方法中遇到了异常,它说“上一个块在解密中不完整” –

回答

-1

我想你是以错误的方式处理光标。

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

rawQuery返回第一个状态之前的游标......只有当您仅获取时才使用moveToNext是非常有效的第一排 – Selvin