您的位置:首页 > 数据库

SQL注入与防范(PreparedStatement的优点)----JDBC-3

2015-12-15 23:41 190 查看
有些人学编程想必一定是受了黑客的影响,看着他们如何牛逼~自己也想向他们一样,黑了别人的网站什么的。

今天说的SQL注入虽然不应定能让你黑了某个网站,或许会让你明白一些黑客入侵的方法,提高自己的防范意识!

/**
* SQL  注入小例
*操作oracle中一个user表,表中只有一个数据:username = Tom,password = 123456
*模拟一种有漏洞的登录方式
*/
@Test
public void testSQLInjection() {

//正常的用户名和密码,可以登录
//		String username = "Tom";
//		String password = "123456";

//SQL注入,添加恶意代码非法登录!!!
String username = "x' or password = ";
String password = "or 'x' = 'x";

//查询语句
String sql = "select * from users where username = '"+username+"' and password = '"+password+"'";
System.out.println(sql);//打印查询语句

Connection connection = null;
Statement statement = null;
ResultSet result = null;

try {
//获取数据库连接,具体方法可看往期博文
connection = getConnection();
statement = connection.createStatement();
result = statement.executeQuery(sql);

//如果数据匹配则表明登录成功
if(result.next()) {
System.out.println("登录成功!");
}else {
System.out.println("登录失败,请检查用户名及密码!");
}

} catch(Exception e) {
e.printStackTrace();
} finally {
//释放相应的资源
if(result != null) {
try {
result.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(statement != null) {
try {
statement.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
}catch (Exception e) {
e.printStackTrace();
}
}

}

}
分析:为什么username = ‘x' or password = '和password = ' or 'x' = 'x'也可以登录成功?很简单我们看看sql语句就知道了

select * from users where username = 'x' or password = ' and password = 'or 'x' = 'x',学过SQL的都知道,

这已经把原来的语句改变,是的语句永远为真,故而可以登录成功。那么有没有什么方法的方法呢?

下面我就来说一说解决办法:用PreparedStatement来替代Statement

示例如下:

/**
* 使用 PreparedStatement 将有效的解决 SQL 注入问题.
* 这也是PreparedStatement相较于Statement的一大优点
*/
@Test
public void testSolutionSQLInjection() {

//SQL注入,添加恶意代码妄图非法登录!!!
String username = "x' or password = ";
String password = "or 'x' = 'x";

//查询语句
String sql = "select * from users where username = ? and password = ?";
System.out.println(sql);

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet result = null;

try {
//连接数据库,具体方法可看往期博文
connection = getConnection();
//使用PreparedStatement
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);

result = preparedStatement.executeQuery();

if(result.next()) {
System.out.println("登录成功!");
}else {
System.out.println("登录失败,请检查用户名及密码!");
}

} catch(Exception e) {
e.printStackTrace();
} finally {
//释放相应的资源
if(result != null) {
try {
result.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(PreparedStatement != null) {
try {
PreparedStatement.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
}catch (Exception e) {
e.printStackTrace();
}
}
<span style="white-space:pre">	</span>}

}


哈哈!结果当然是失败咯~

如有不足请多多指教

如果对你有帮助请点赞支持
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: