How to solve the problem of sql injection

Java prevent SQL injection

Introduction to SQL Injection:
SQL injection is one of the most common attacks, it is not using the operating system vulnerabilities or other systems to achieve the attack, but because programmers do not judge, was drilled loopholes SQL unscrupulous user, the following let's look at what is SQL injection:

    比如在一个登陆界面,要求用户输入用户名和密码:

    用户名:     ' or 1=1 --   

    密     码:   

    点登陆,如若没有做特殊处理,而只是一条带条件的查询语句如:

    String sql="select * from users where username='"+userName+"' and password='"+password+"' "

    那么这个非法用户就很得意的登陆进去了.(当然现在的有些语言的数据库API已经处理了这些问题)

    这是为什么呢?我们来看看这条语句,将用户输入的数据替换后得到这样一条语句:

    select * from users where username='' or 1=1 --' and password=''

    为了更明白些,可以将其复制到SQL分析器中,将会发现,这条语句会将数据库的数据全部读出来,为什么呢?

    很简单,看到条件后面 username='' or 1=1 用户名等于 '' 或 1=1 那么这个条件一定会成功,然后后面加两个-,这意味着什么?

   Yes, comments, statements Notes behind it, so that they do not work, so you can smooth the data in the database is read out.

    这还是比较温柔的,如果是执行 
    select * from users where username='' ;DROP Database    (DB Name) --' and password=''

    .......其他的您可以自己想象。。。

    那么我们怎么来处理这种情况呢?下面我以java为列给大家两种简单的方法:

    **第一种采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setString方法传值即可:**
    String sql= "select * from users where username=? and password=?;
    PreparedStatement preState = conn.prepareStatement(sql);
    preState.setString(1, userName);
    preState.setString(2, password);
    ResultSet rs = preState.executeQuery();
    ...

    **第二种是采用正则表达式将包含有 单引号('),分号(;) 和 注释符号(--)的语句给替换掉来防止SQL注入**
    public static String TransactSQLInjection(String str)
    {
          return str.replaceAll(".*([';]+|(--)+).*", " ");

       // 我认为 应该是return str.replaceAll("([';])+|(--)+","");

    }

    userName=TransactSQLInjection(userName);
    password=TransactSQLInjection(password);

    String sql="select * from users where username='"+userName+"' and password='"+password+"' "
    Statement sta = conn.createStatement();
    ResultSet rs = sta.executeQuery(sql);
Published 77 original articles · won praise 39 · views 80000 +

Guess you like

Origin blog.csdn.net/qq_33824312/article/details/76263068