.NET MVC5之网站安全

坚强是说给别人听的谎言 提交于 2020-04-24 14:32:54

XSS(脚本攻击)

使用AntiXSS Library的AntiXssEncoder

public static String SafeHtml(this string helper,string str)
{
    var filterString = str == null ? "" : str.Trim();

    if (string.IsNullOrWhiteSpace(filterString))
        return null;
    var regex = new Regex(@"<(?!br|\/?p|style|\/?span)[^>]*>");
    filterString = regex.Replace(filterString,"");
    return filterString;
}

CSRF或XSRF(跨网站伪造请求)

  • 写入后端的数据都是用POST
  • 限制POST的Action不接受GET
  • 在服务器端判断数据的来源,Html.AntiForgeryToken()

加密与解密

  1. 增加密码的复杂度:长度至少8位,至少有一个大小写英文,至少包含一个数字
  2. 密码存储:哈希(hash)加密后存储

窗体验证原则

  1. 使用https
  2. 使用http post
  3. 对数据校验
  4. 不要使用隐藏字段
  5. 不要提示过多的错误信息
  6. 使用captcha技术

ASP.NET加密技术--System.Security.Cryptography

  • 对称算法:DES,3DS,Rjindael(AES),RC2:大量数据加密
  • 非对称算法:RSA:验证,数据完整性
  • 哈希算法:MD5,SHA1,SHA256,SHA384,SHA512,DSA:数据完整性

SHA256,SHA384,SHA512,:密码加密是比较安全的。

public static string SHA256Encryptor(string plainText) {
    Byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText);
    SHA256 sHA256 = new SHA256CryptoServiceProvider();
    byte[] result = sHA256.ComputeHash(data);
    return Convert.ToBase64String(result);
}

带有密钥的哈希密码

public static string GuidWithPassword(Guid guid,string plainText) {
    Byte[] data = ASCIIEncoding.ASCII.GetBytes(guid+plainText);
    SHA256 sHA256 = new SHA256CryptoServiceProvider();
    byte[] result = sHA256.ComputeHash(data);
    return Convert.ToBase64String(result);
}

Crypto类

Crypto类将最常用的哈希算法进行再封装

GenerateSalt(Int32)    Generates a cryptographically strong sequence of random byte values.

Hash(Byte[], String)    Returns a hash value for the specified byte array.

Hash(String, String)    Returns a hash value for the specified string.

HashPassword(String)    Returns an RFC 2898 hash value for the specified password.

SHA1(String)    Returns a SHA-1 hash value for the specified string.

SHA256(String)    Returns a SHA-256 hash value for the specified string.

VerifyHashedPassword(String, String)    Determines whether the specified RFC 2898 hash and password are a cryptographic match.

加密web.config

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!