asp.net DES加解密
程序员文章站
2024-03-13 23:22:22
...
对称加密DES,用来加解密。(MD5非对称加密无法解密,一般用来加密密码,登录时加密对比字符串)
/// <summary>
/// 对称DES加密解密
/// </summary>
public class DESEncrypt
{
//自定义口令
private static string key = "1dowbndk";
/// <summary>
/// 对称加密解密的**
/// </summary>
public static string Key
{
get
{
return key;
}
set
{
key = value;
}
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="encryptString"></param>
/// <returns></returns>
public static string DesEncrypt(string encryptString)
{
try
{
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();
string result= Convert.ToBase64String(mStream.ToArray());
mStream.Close();
cStream.Close();
return result;
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="decryptString"></param>
/// <returns></returns>
public static string DesDecrypt(string decryptString)
{
try
{
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();
string result = Encoding.UTF8.GetString(mStream.ToArray());
mStream.Close();
cStream.Close();
return result;
}
catch (Exception)
{
return "";
}
}
}