數據庫注入攻擊和防止注入攻擊

 Java程序實現用戶登錄,用戶名和密碼,數據庫檢查

 演示被別人注入攻擊

public class userdenglu {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//密碼和用戶名寫死的情況下的注入攻擊
		//用戶名和密碼由用戶輸入
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/mydatabase";
		String username = "root";
		String password = "12345678";
		Connection con = DriverManager.getConnection(url,username,password);
		Statement stat = con.createStatement();
		//執行SQL語句,數據表,查詢用戶名和密碼,如果存在,登錄成功,不存在登錄失敗
		Scanner sc = new Scanner(System.in);
		String user = sc.nextLine();
		String pass = sc.nextLine();
		String sql = "select * from pass where uname = '"+user+"' and upassword = '"+pass+"'";
		ResultSet rs = stat.executeQuery(sql);
		/*while(rs.next()){
			System.out.println(rs.getString("uname")+"  "+rs.getString("upassword"));
		}*/
		if(rs.next()){
			System.out.println("登錄成功");
			System.out.println(sql);
			System.out.println(rs.getString("uname")+"  "+rs.getString("upassword"));
		}else{
			System.out.println("用戶名或者密碼錯誤");
		}
		rs.close();
		stat.close();
		con.close();
	}

}


防止注入攻擊:使用PreparedStatement來解決對應的問題。

當用戶輸入正確的賬號與密碼後,查詢到了信息則讓用戶登錄。但是當用戶輸入的賬號爲XXX 密碼爲:XXX’  OR ‘a’=’a時,則真正執行的代碼變爲:

SELECT * FROM 用戶表 WHERE NAME = ‘XXX’ AND PASSWORD =’ XXX’  OR ’a’=’a’;

實例:

public class preparestatementdemo {
	/*
	 * java程序實現用戶登錄,用戶名和密碼,數據庫檢查
	 * 防止注入攻擊
	 * Statement接口實現類,作用執行SQL語句,返回結果集
	 * 有一個子接口PreparedStatement,其中在Connection類中有數據庫連接對象的方法:
	 * PreparedStatement preparedStatement(String sql)
	 * 
	 */
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/mydatabase";
		String username = "root";
		String password = "12345678";
		Connection con = DriverManager.getConnection(url,username,password);
		//執行SQL語句,數據表,查詢用戶名和密碼,如果存在,登錄成功,不存在登錄失敗
		Scanner sc = new Scanner(System.in);
		String user = sc.nextLine();
		String pass = sc.nextLine();
		String sql = "select * from pass where uname = ? and upassword = ?";
		//調用Connection接口中的方法 PreparedStatement prepareStatement(String sql) 
		//方法中參數,SQL語句中的參數全部採用問號佔位符
		PreparedStatement pst = con.prepareStatement(sql);
		//調用pst對象set方法,設置問號佔位符上的參數
		pst.setObject(1, user);
		pst.setObject(2, pass);
		//調用方法,執行SQL,獲取結果集
		ResultSet rs = pst.executeQuery();
		/*while(rs.next()){
			System.out.println(rs.getString("uname")+"  "+rs.getString("upassword"));
		}*/
		if(rs.next()){
			System.out.println("登錄成功");
			System.out.println(sql);
			System.out.println(rs.getString("uname")+"  "+rs.getString("upassword"));
		}else{
			System.out.println("用戶名或者密碼錯誤");
		}
		rs.close();
		pst.close();
		con.close();
	}
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章