Fork me on GitHub

网站会员密码

   这几天因为CSDN明文密码泄露的事情闹得沸沸扬扬.在年关将至的时候火了一把.让我想起我们项目中的会员密码是如何保存的?

   这部分代码是之前曹哥或张博士所留,平常虽然有看过,但也没有仔细研究,只记得有HASH有Salt(盐?).但到底如何实现,今天就当作复习了一下.

   思路以前有所了解,首先产生一个5位数的Salt,然后将password和salt进行Hash.但是具体代码的实现,确实没有了解.

 

产生Salt:

        /// <summary>
        /// 产生随机的混入字符串
        /// </summary>
        /// <param name="length">产生的字符串的长度</param>
        /// <returns>随机字符串</returns>
        public static string CreateSalt(int length)
        {
            Random r = new Random();
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                sb.Append(constant[r.Next(constant.Length)]);
            }
            return sb.ToString();
        }

 在salt产生中使用了一个constant的数组:

  private static char[] constant ={'0','1','2','3','4','5','6','7','8','9',
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
        's','t','u','v','w','x','y','z',
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
        'S','T','U','V','W','X','Y','Z' };

 将password和salt混入并Hash:

 /// <summary>
        /// 混入并计算Hash值
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <param name="salt">混入字符串</param>
        /// <returns>混入后字符串的Hash值</returns>
        public static string SaltAndHash(string rawString, string salt)
        {
            string plan = string.Concat(rawString, salt);
            return plan.Hash();
        }

 hash算法:

  /// <summary>
        /// 计算字符串的Hash值
        /// </summary>
        /// <param name="planText">明文</param>
        /// <returns>Hash值</returns>
        public static string Hash(this string planText)
        {
            byte[] plan = Encoding.UTF8.GetBytes(planText);

            SHA256 hasher = new SHA256Managed();
            byte[] hashed = hasher.ComputeHash(plan);

            return Convert.ToBase64String(hashed);
        }
posted @ 2012-01-11 17:15  idoku  阅读(271)  评论(0编辑  收藏  举报