您的位置:首页 > 数据库

为什么参数化SQL查询可以防止SQL注入?

2016-12-16 08:46 519 查看
为什么参数化SQL查询可以防止SQL注入?

回答
关注 (4)

微博
微信
QQ空间

1个回答



专业喷MI
12-15 16:53
0赞


1. 参数化预编译之所以能防御住SQL注入,只要是基于以下2点:

1) setString(): WEB程序接收字符串的场景

将用户输入的参数全部强制转换为字符串,并进行适当的转义,防止了闭合的产生

2) setInt(): WEB程序接收整型的场景

将用户输入的非整型参数强制转换为整型,并去除潜在的"非整型注入字符",类似与PHP中的intVal()防御思路

2. 并不是说使用了参数化预编译方法执行SQL,就不会有注入的发生了,当WEB系统和DataBase系统的字符集配置不当,

也可能会导致宽字节注入的发生

参数化查询例子:

class DBExample

{

private static string connectionString = "Data Source=.;Initial Catalog=Test;Integrated Security=True";

static void Main(string[] args)

{

MyLogin("b", "a");

MyLogin("b' or 1=1--", "a");

}

private static void MyLogin(string userName, string password)

{

using (SqlConnection conn = new SqlConnection(connectionString))

{

conn.Conn();

SqlCommand comm = new SqlCommand();

comm.Connection = conn;

comm.CommandText = "select COUNT(*) from userinfo where Password = @Password and UserName = @UserName";

comm.Parameters.AddRange(

new SqlParameter[]{

new SqlParameter("@Password", SqlDbType.VarChar) { Value = password},

new SqlParameter("@UserName", SqlDbType.VarChar) { Value = userName},

});

comm.ExecuteNonQuery();

}

}

}

实际执行的SQL:

exec sp_executesql N'select COUNT(*) from userinfo where Password = @Password and UserName = @UserName',N'@Password varchar(1),@UserName varchar(1)',@Password='a',@UserName='b'

exec sp_executesql N'select COUNT(*) from userinfo where Password = @Password and UserName = @UserName',N'@Password varchar(1),@UserName varchar(11)',@Password='a',@UserName='b'' or 1=1—'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: