积极答复者
C# MD5 加密,为什么有那么多种写法?

问题
答案
-
Hi,
其实不用管有多少种写法,最终的目的是为了更安全的保存数据。一般的做法是将用户输入的密码与一个随机生成的 Guid 拼接成一个长的字符串,然后使用.Net Framework 中的 MD5 对象计算出一个对应的MD5值并将其与对应的 Guid 存入数据库中,当用户登录的时候就使用登录窗口传入的密码与 Guid 再次计算出一个新的MD5值并与数据库中的MD5值进行比对。这样做就可以实现数据库中不存储用户的密码数据(即非明文保存)。
请参照以下代码:
public static string Md5Hash(string input, Guid salt) { return Md5Hash(string.Format(CultureInfo.InvariantCulture, "{0}{1}", input, salt)); } public static string Md5Hash(string input) { using (var md5Hash = MD5.Create()) { // Convert the input string to a byte array and compute the hash. var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // Return the hexadecimal string. return sBuilder.ToString(); } }
Please mark this as answer if it helps with this issue!
- 已建议为答案 ThankfulHeartModerator 2013年9月19日 6:19
- 已标记为答案 Barry WangModerator 2013年10月7日 10:10
全部回复
-
Hi,
其实不用管有多少种写法,最终的目的是为了更安全的保存数据。一般的做法是将用户输入的密码与一个随机生成的 Guid 拼接成一个长的字符串,然后使用.Net Framework 中的 MD5 对象计算出一个对应的MD5值并将其与对应的 Guid 存入数据库中,当用户登录的时候就使用登录窗口传入的密码与 Guid 再次计算出一个新的MD5值并与数据库中的MD5值进行比对。这样做就可以实现数据库中不存储用户的密码数据(即非明文保存)。
请参照以下代码:
public static string Md5Hash(string input, Guid salt) { return Md5Hash(string.Format(CultureInfo.InvariantCulture, "{0}{1}", input, salt)); } public static string Md5Hash(string input) { using (var md5Hash = MD5.Create()) { // Convert the input string to a byte array and compute the hash. var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // Return the hexadecimal string. return sBuilder.ToString(); } }
Please mark this as answer if it helps with this issue!
- 已建议为答案 ThankfulHeartModerator 2013年9月19日 6:19
- 已标记为答案 Barry WangModerator 2013年10月7日 10:10