JDBC中的sql注入问题

  • SQL注入

      SQL注入即是指web应用程序对用户输入数据的合法性没有判断或过滤不严,
      攻击者可以在web应用程序中事先定义好的查询语句的结尾上添加额外的SQL语句,
      在管理员不知情的情况下实现非法操作,
      以此来实现欺骗数据库服务器执行非授权的任意查询,
      从而进一步得到相应的数据信息。
      该问题存在于Statement接口中
      在它的子接口PreparedStatement中该问题得到了解决
      那我们就在使用Statement接口的情况下展示sql注入
    
  • 原表数据
    原表

  • 根据账户密码查询该人信息

package com.mystudy.jdbc;

import java.sql.*;

public class SqlInject {
    public static void login(String username,String password) throws ClassNotFoundException, SQLException {
        //forName抛出异常 ClassNotFoundException
        Class.forName("com.mysql.jdbc.Driver");
        //getConnection 抛出异常SQLException
        Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?useSSL=true","root","root");
        Statement st=conn.createStatement();
        String sql ="SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'";
        ResultSet rs=st.executeQuery(sql);
        while (rs.next()){
            System.out.print(rs.getInt(1));
            System.out.print(rs.getString(2));
            System.out.print(rs.getString(3));
            System.out.print(rs.getDate(4));
            System.out.print(rs.getString(5));
            System.out.println(rs.getString(6));
        }
        //资源释放
        rs.close();
        st.close();
        conn.close();
    }
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        login("hhh","123456");
    }
}


结果:
正常登录查询结果

  • sql注入情况
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
      //login("hhh","123456");
        login("'or'1=1", "'or'1=1");
    }

结果:盗出了所有用户信息
sql注入后的登录查询结果

代码解释:

  • 正常情况下:
    "SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'"
    login("hhh","123456");带入
    "SELECT * FROM student where stu_user='hhh' and stu_password='123456'"
  • sql注入情况登录:
    "SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'"
    login("'or'1=1", "'or'1=1");带入
    "SELECT * FROM student where stu_user=''or'1=1' and stu_password=''or'1=1'"
  • 这里建议再学习一下事务回滚:事务回滚
  • 这里有JDBC的入门学习流程:入门学习流程
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值