• 【转载】C#检测客户端输入的内容是否含有危险字符串


    用户在客户端提交的内容有时候并不可信,如果客户端提交的内容中含有危险字符串信息,则很有可能造成应用程序安全性问题,如SQL注入风险等。因此在接收客户端提交过来的数据后,我们首先需要判断数据中是否含有危险字符信息,如果有则可以提前处理掉,如去除一些SQL注入攻击的关键字等。

    校验的方法封装如下:

     /// <summary>
            /// 检测客户输入的字符串是否有效,并将原始字符串修改为有效字符串或空字符串。
            /// 当检测到客户的输入中有攻击性危险字符串,则返回false,有效返回true。
            /// </summary>
            /// <param name="input">要检测的字符串</param>
            public static bool IsValidInput(ref string input)
            {
                try
                {
                    if (IsNullOrEmpty(input))
                    {
                        //如果是空值,则跳出
                        return true;
                    }
                    else
                    {
                        //替换单引号
                        input = input.Replace("'", "''").Trim();
                        //检测攻击性危险字符串
                        string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
                        string[] testArray = testString.Split('|');
                        foreach (string testStr in testArray)
                        {
                            if (input.ToLower().IndexOf(testStr) != -1)
                            {
                                //检测到攻击字符串,清空传入的值
                                input = "";
                                return false;
                            }
                        }
                        //未检测到攻击字符串
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

    备注:原文转载自C#检测客户端输入的内容是否含有危险字符串_IT技术小趣屋

    博主个人技术交流群:960640092,博主微信公众号如下:

  • 相关阅读:
    Oracle SQL语句记录
    Gvim 在进行文件对比时报cannot read or write temp files
    Java Lock
    Java Synchronized
    CLH锁 、MCS锁
    JVM 运行时内存结构
    XSS攻击及防御
    Java IO 技术之基本流类
    Java 对象的串行化(Serialization)
    Java final关键字
  • 原文地址:https://www.cnblogs.com/xu-yi/p/10577559.html
Copyright © 2020-2023  润新知