此登录代码是否容易受到SQL注入攻击?

时间:2014-01-31 03:31:51

标签: java sqlite sql-injection

String sSQL = "select RFC,Contraseña from Administradores where RFC='" + txtUsuario.getText() + "' and Contraseña='" + txtContrasena.getText() + "'";

String[] registros = new String[2];
Try  {
    conect();
    conexion = DriverManager.getConnection("jdbc:sqlite:" + base);
    Statement stat = conexion.createStatement();
    ResultSet rs = stat.executeQuery(sSQL);
    while (rs.next()) {
        registros[0] = rs.getString("RFC");
        registros[1] = rs.getString("Contraseña");
    }
    stat.close();
    conexion.close();
} catch (SQLException ex)    
{    
    JOptionPane.showMessageDialog(null,"DB connection error");    
}
if ((txtContrasena.getText().equals(registros[1])) || (txtUsuario.getText().equals(registros[0]))) {
    JOptionPane.showMessageDialog(null, "Access Granted");
    Escoger variable = new Escoger();
    variable.setVisible(true);
    dispose();
} else {
    if (txtContrasena.getText() != (registros[1])) {
        JOptionPane.showMessageDialog(null, "Incorrect password");
    }
}

3 个答案:

答案 0 :(得分:3)

此...

String sSQL = "select RFC,Contraseña from Administradores where RFC='" + 
              txtUsuario.getText() + "' and Contraseña='" + 
              txtContrasena.getText() + "'";

会自动建议它。输入txtUsuariotxtContrasena的任何内容都可能包含可由数据库的SQL引擎执行的有效SQL代码。

您应该使用:

String sSQL = "select RFC,Contraseña from Administradores where RFC=? and Contraseña=?";

然后你需要改变......

Statement stat = conexion.createStatement();

PreparedStatement stat = conexion.preapreStatement(sSQL);
stat.bindString(1, txtUsuario.getText());
stat.bindString(2, txtContrasena.getText());

请查看Using Prepared Statements了解详情

答案 1 :(得分:3)

此外,您不应该在数据库中存储密码。您应该在数据库中存储密码的散列版本,并检查密码您散列的内容(安全,https,如果通过Web),并将该散列值与数据库中的散列值进行比较。使用安全散列算法(例如,不是MD5)。更好的是,连接用户名和密码以及散列,然后将其用作存储在数据库中的值并进行比较(这样两个具有相同密码的用户不会散列到相同的值)。

答案 2 :(得分:0)

是。请改用PreparedStatements。用占位符替换用户和密码值。

String SampleQuery = "SELECT * FROM YourTable WHERE User = ? AND Password = ?";
String UserName = UsernameBox.getText();
String Password = PasswordBox.getText();

PreparedStatement prep = conn.prepareStatement(SampleQuery);
prep.setString(1, UserName);
prep.setString(2, Password);
ResultSet result = prep.executeQuery();