一、概述:
SQL注入攻击指的是通过构建特殊的输入作为参数传入Web应用程序,而这些输入大都是SQL语法里的一些组合,通过执行SQL语句进而执行攻击者所要的操作,其主要原因是程序没有细致地过滤用户输入的数据,致使非法数据侵入系统。
以模拟登录为例:在前台输入用户名和密码,后台判断信息是否正确,并给出前台反馈信息,前台输出反馈信息
二、创建数据库表
二、测试代码
//创建Account对像
package com.xianyu;import java.io.Serializable;public class Account implements Serializable {private int aid;private String username;private String password;private Double money;@Overridepublic String toString() {return "Account{" +"aid=" + aid +", username='" + username + '\'' +", password='" + password + '\'' +", money=" + money +'}';}public Account(int aid, String username, String password, Double money) {this.aid = aid;this.username = username;this.password = password;this.money = money;}public Account() {}public int getAid() {return aid;}public void setAid(int aid) {this.aid = aid;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}
}
//调用Account对像
package com.xianyu;import java.sql.*;
import java.util.Scanner;public class TestInjection {private static String driver ="com.mysql.cj.jdbc.Driver";private static String url="jdbc:mysql://localhost:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";private static String user ="root";private static String password="12345678";public static void main(String[] args) {Scanner sc =new Scanner(System.in);System.out.print("请输入用户名:");String username=sc.next();System.out.print("请输入密码:");String pwd =sc.next();Account account = getAccount(username, pwd);System.out.println(null!= account?"登录成功":"登录失败");sc.close();}public static Account getAccount(String username,String pwd){Connection connection = null;Statement statement=null;ResultSet resultSet=null;Account account =null;try{Class.forName(driver);connection = DriverManager.getConnection(url, user,password);statement = connection.createStatement();String sql="select * from account where username ='"+username+"' and password ='"+pwd+"'";System.out.println(sql);resultSet = statement.executeQuery(sql);while(resultSet.next()){int aid = resultSet.getInt("aid");String usernamea = resultSet.getString("username");String pwda = resultSet.getString("password");double money = resultSet.getDouble("money");account=new Account(aid,usernamea,pwda,money);System.out.println(account);}}catch (Exception e){e.printStackTrace();}finally {if(null != resultSet){try {resultSet.close();} catch (SQLException e) {e.printStackTrace();}}if(null != statement){try {statement.close();} catch (SQLException e) {e.printStackTrace();}}if(null != connection){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}return account;}
}
正常的测试结果:
输入正确的用户名密码
SQL注入攻击测试结果
当密码后面加入 1'or'1'='1 时,登陆成功
sql注入防范