字符串的加解密
为了方便对于字符串的加解密,.NET提供了一些内置支持。一般我们更愿意把它们封装成一个通用类,以重复使用.下面是一个范例
public class Encrypter
{
private SymmetricAlgorithm mCSP;
private const string CIV = "kXwL7X2+fgM=";
private const string CKEY = "FwGQWRRgKCI=";
public Encrypt()
{
mCSP = new DESCryptoServiceProvider();
}
///对称加密
public string EncryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
///对称解密
public string DecryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
///产生哈希散列值
public string Hashed(string input)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] byt = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(md5.ComputeHash(byt));
}
///比较哈希值(注意,哈希算法是不可逆的,所以只能进行比较
public bool CompareHash(string input, string hashedstring) {
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
return hashedstring.Equals(Hashed(input));
}
}
客户程序调用的例子
public static void Main()
{
Encrypter encrypt = new Encrypter();
Console.WriteLine(encrypt.EncryptString("Hello,world"));
Console.WriteLine(encrypt.DecryptString("sHwFBA84ozrLqSMYRrAKIw=="));
Console.WriteLine(encrypt.Hashed("chenxizhang"));
Console.WriteLine(encrypt.CompareHash("chenxizhang", "xLl6tY7Js1JpbssgopzBhg=="));
Console.Read();
}