Introduction to SQL Injection:
SQL injection is one of the most common attack methods, it is not the use of the operating system or other system vulnerabilities to achieve attacks, but the programmer because not good judgment, was illegal
The user has drilled a loophole in SQL, let's take a look at what SQL injection is:
For example, in a login interface, users are required to enter the user name and password:
User name: ' or 1=1--
Password
Point Landing, if not to do special processing, but only a conditional query statements such as:
String sql= "SELECT * from Users where username= '" +username+ "' and password= '" +password+ "'"
Then this illegal user will be very proud of landing in. (Of course, some languages now have database APIs that address these issues.)
What is this for? Let's take a look at this statement and replace the data entered by the user with a statement like this:
SELECT * from users where username= ' or 1=1--' and password= '
To be more clear, you can copy it into the SQL parser and you'll see that this statement reads all the data from the database.
Very simple, see the condition behind username= ' or 1=1 username equals ' or 1=1 then this condition will be successful and then add two--which means
What the? Yes, the comment, which comments the following statements so that they do not work, so that the data in the database can be successfully read out.
This is still relatively gentle, if it is performed
SELECT * from users where username= ';D rop Database (DB Name)--' and password= '
....... Others you can imagine ...
So how do we deal with this situation? Here I will give you two simple methods of Java:
The first is a set of precompiled statements that has the ability to handle SQL injection, as long as it uses its SetString method to pass values:
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 ();
...
The second is to use a regular expression that will contain the single quotation mark ('), semicolon (;) and comment symbols (--) are replaced by statements to prevent SQL injection
public static string Transactsqlinjection (String str)
{
Return Str.replaceall (". *" ([';] +| (--)+).*", " ");
I think it should be 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);
java prevents SQL injection