,.NET提供了一个专门用于做Password Hashing的方法
public static string HashPasswordForStoringInConfigFile (
string password,
string passwordFormat
)
第一个参数password就是密码,而第二个参数则是要使用的Hash算法,这个值只能是FormsAuthPasswordFormat枚举的成员(位于System.Web.Configuration下),不过不清楚为什么不直接传枚举类型。FormsAuthPasswordFormat有三个枚举成员,它们是Clear、MD5、SHA1,其中的Clear就是不加密,直接用明文的意思。
大家可以参考:http://msdn2.microsoft.com/en-us/library/system.web.security.formsauthentication.hashpasswordforstoringinconfigfile.aspx
public class PasswordHelper
{
public static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
public static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "sha1");
return hashedPwd;
}
public static bool PasswordMatch(string current,string salt,string savedPasswordHash)
{
string currentPasswordHash=CreatePasswordHash(current, salt);
return (currentPasswordHash == savedPasswordHash);
}
}