用Java编写rawQuery来停止sql注入

时间:2016-11-08 01:14:23

标签: android sqlite data-binding prepared-statement

我试图证明我当前的代码停止阻止sql注入。同时我正在努力学习编写一个使用的rawQuery?对于占位符。 我的表如下:

public static final String TABLE_NAME = "masterPW";
public static final String Col_ID = "ID";
public static final String Col_MPW = "mpw";

当MainActivity启动时,它通过调用转到下面的DBHelper类代码的onLoad方法来检查Col_MPW是否有数据

    private void onLoad(){

    dbHelper = new DBHelper( this );
    str = dbHelper.getCol_MPW();
    // Line of code above calls getCol_MPW method in DBHelper
    // And DBHwlper RETURNS str Variable with the Master Password
    //============================================================
    if (str == null || str.isEmpty()) {
        etPW.requestFocus();
        btnSave.setVisibility( View.VISIBLE );
        System.out.println( "I am NULL" );
    } else {
        setTitle( "Enter Password "+str );
        tvCPW.setVisibility( View.INVISIBLE );
        etCPW.setVisibility( View.INVISIBLE );
        btnSave.setVisibility( View.INVISIBLE );
        btnEnter.setVisibility( View.VISIBLE );
        System.out.println( "Im NOT NULL "+str );
    }
}

好的,现在我们将说密码已经创建,当用户输入密码进入下一个活动时,我们调用onLoad抓取TABLE中的值并将其返回给MainActivity并进行预成型验证 下面的代码在DBHelper中,并返回一个字符串进行验证

    public String getCol_MPW(){
    String str = null;
    db = getReadableDatabase();

    String q = "SELECT mpw FROM masterPW";
    //String q = "SELECT * FROM masterPW";
    //String ov = etPW.getText().toString();
    //Cursor cursor = db.rawQuery("SELECT mpw "+"FROM  masterPW"+"WHERE mpw = ? ",new String[]{ov};
    // The line of  CODE above  fails even when I  replase ov with the PASSWORD
    //=================================================================
    Cursor cursor = db.rawQuery(q,null);

    if(cursor.moveToFirst()){
        str = cursor.getString(cursor.getColumnIndex(Col_MPW));
    }
    cursor.close();
    db.close();

    return str;
}

然后使用此代码验证返回MainActivity的str

    public void onEnter(View view) {

    // Will use REGEX here so matches is ok
    // But with NO REGEX -> MUST <- use equals

    //if (str.matches( etPW.getText().toString().trim() )) {
        if(str.equals(etPW.getText().toString().trim())){
        etPW.setText( "" );
        str = "";
        Intent intent = new Intent( MainActivity.this, PageTwo.class );
        startActivity( intent );
    } else {
        Toast.makeText( MainActivity.this, "Incorrect Password", Toast.LENGTH_LONG ).show();
        etPW.requestFocus();
    }
}

我在DBHelper中的代码public String getCol_MPW()在NON sql注入代码注释掉了我的一些非生产性尝试。那说我也尝试了各种sql注入技术来通过我的验证没有人会工作。 所以我仍然希望对如何实现更好的rawQuery方法以防止sql注入有一些指导?在密码之后我需要将其他数据添加到数据库中。我已经查看了预处理语句和绑定但是如果我不能用只有一行的表来实现它,那么我认为没有必要进一步了解

0 个答案:

没有答案