1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class JDBCDemo3 { public static void demo3_1(){ boolean flag=login( "aaa' OR ' " , "1651561" ); // 若已知用户名,用这种方式便可不用知道密码就可登陆成功 if (flag){ System.out.println( " 登陆成功" ); } else { System.out.println( " 登陆失败" ); } } public static boolean login(String username,String password){ Connection conn= null ; Statement stat= null ; ResultSet rs= null ; boolean flag= false ; try { conn=JDBCUtils.getConnection(); String sql= "SELECT * FROM user WHERE username='" +username+ "'AND password='" +password+ "'" ; // 此处是SQL注入漏洞的关键,因为是字符串的拼接,会使查询语句变为:SELECT * FROM user WHERE username='aaa' OR '' AND password='1651561',此查询语句是可得到结果集的,便出现此漏洞 stat=conn.createStatement(); rs=stat.executeQuery(sql); if (rs.next()){ flag= true ; } else { flag= false ; } } catch (SQLException e) { e.printStackTrace(); } return flag; } |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public static void demo3_1(){ boolean flag=login1( "aaa' OR ' " , "1651561" ); if (flag){ System.out.println( " 登陆成功" ); } else { System.out.println( " 登陆失败" ); } } public static boolean login1(String username,String password){ Connection conn= null ; PreparedStatement pstat= null ; ResultSet rs= null ; boolean flag= false ; try { conn=JDBCUtils.getConnection(); String sql= "SELECT * FROM user WHERE username=? AND password=?" ; // 使用?代替参数,预先设置好sql格式,就算在输入sql关键字也不会被sql识别 pstat=conn.prepareStatement(sql); pstat.setString( 1 ,username); // 设置问号的值 pstat.setString( 2 ,password); rs=pstat.executeQuery(); if (rs.next()){ flag= true ; } else { flag= false ; } } catch (SQLException e) { e.printStackTrace(); } return flag; } } |
相关文章