您的位置:首页 > 编程语言 > ASP

asp.net中利用加密盐进行加密字符串

2006-09-22 13:46 549 查看
asp.net中提供了很多的加密算法,如:SHA1,MD5... ,同时还提供了一种加密盐(salt)机制。

加密盐就是通过salt和字符串混合加密得出的(salt称为盐,是一串随机字符串,如果salt不一样则加密出来的结果也是不一样的)

由于salt是一个随机数因此下面两个按钮中执行的结果也是不一样的!

废话少说,还是给出相应的代码:

#region ---生成加密盐
public string CreateSalt(int size)
{
//使用加密服务提供程序 (CSP) 提供的实现来实现加密随机数生成器 (RNG).
//using System.Security.Cryptography;

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
//返回Base64字符串表示形式的随机数
return Convert.ToBase64String(buff);

}
#endregion
#region ---SHA1+Salt进行加密
private string createPwdHashSHA1(string pwd, string salt)
{
string saltAndPwd = string.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1");
return hashedPwd;
}
#endregion

#region ---MD5+Salt进行加密
private string createPwdHashMD5(string pwd, string salt)
{
string saltAndPwd = string.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "MD5");
return hashedPwd;
}
#endregion
#region ---进行加密
protected void Button1_Click(object sender, EventArgs e)
{
string salt = this.CreateSalt(32);
Label7.Text = this.createPwdHashSHA1(TextBox1.Text, salt);//salt+sha1
Label6.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "SHA1");//sha1
Label8.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "MD5");//md5
Label9.Text = this.createPwdHashMD5(TextBox1.Text, salt);//md5+salt
}
#endregion
protected void Button2_Click(object sender, EventArgs e)
{
string salt = this.CreateSalt(32);
Label11.Text = this.createPwdHashSHA1(TextBox1.Text, salt);//salt+sha1
Label10.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "SHA1");//sha1
Label12.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "MD5");//md5
Label13.Text = this.createPwdHashMD5(TextBox1.Text, salt);//md5+salt
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: