asp.net 加密
时间:2011-02-22 来源:双魂人生
MD5:(不可逆的加密)
我们可以使用C#自带的类MD5CryptoServiceProvider去实现
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string 加密后的密码=BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(原密码))).Replace("-","");
或者
public string Encrypt1(string password)
{ //获取byte数组
Byte[] clearBytes = new UnicodeEncoding().GetBytes(password);
//获取hash值
Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
//获取加密后的信息
return BitConverter.ToString(hashedBytes);
}
DES:(可逆的加密)
加密
string key="加密钥匙";
public string Encrypt(string encryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor (keyBytes,keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
解密:
public string Decrypt(string decryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
网上的加密方式很多,最好结合自己修改的,要不同种加密算法,别人同样也会知道...