C#MD5加密和DES加密解密算法
2013-06-24 10:38 C#与.NET探索者 阅读(542) 评论(0) 编辑 收藏 举报public partial class stringTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/*
string s = "i am programmer";
var arr = s.Split(' ');
for (int i = arr.Length - 1; i >= 0; i--)
{
Response.Write(arr[i]+" ");
}*/
//加密测试
string test = "邹大侠";
string vkey = "zpc870921";
Response.Write(string.Format("源字符串:{0}<br/>",test));
string encrypResult = EncryptDes(test,vkey);
Response.Write(string.Format("DES加密后字符串:{0}<br/>", encrypResult));
string decryptResult = DecryptDes(encrypResult, vkey);
Response.Write(string.Format("DES解密后字符串:{0}<br/>", decryptResult));
Response.Write(string.Format("32位MD5加密:{0}<br/>", MD5Encrypt(test)));
}
/// <summary>
/// 32位md5加密算法
/// </summary>
/// <param name="toencrypt"></param>
/// <returns></returns>
private string MD5Encrypt(string toencrypt)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] s = Encoding.UTF8.GetBytes(toencrypt);
byte[] hashbyte = md5.ComputeHash(s);
StringBuilder sb = new StringBuilder();
foreach(var item in hashbyte)
{
sb.AppendFormat("{0:X2}",item);
}
return sb.ToString();
}
/// <summary>
/// DES对称秘钥加密算法
/// </summary>
/// <param name="toencrypt"></param>
/// <param name="vkey"></param>
/// <returns></returns>
private string EncryptDes(string toencrypt,string vkey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.IV = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(vkey,"md5").Substring(0,8));
des.Key = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(vkey,"md5").Substring(0,8));
MemoryStream ms = new MemoryStream();
byte[] s=Encoding.UTF8.GetBytes(toencrypt);
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(s, 0, s.Length);
cs.FlushFinalBlock();
cs.Close();
}
string result = Convert.ToBase64String(ms.ToArray());
return result;
}
/// <summary>
/// DES对称秘钥解密
/// </summary>
/// <param name="toencrypt"></param>
/// <param name="vkey"></param>
/// <returns></returns>
private string DecryptDes(string toencrypt,string vkey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(vkey,"md5").Substring(0,8));
des.IV = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(vkey, "md5").Substring(0, 8));
byte[] s = Convert.FromBase64String(toencrypt);
MemoryStream ms = new MemoryStream(s);
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader sr=new StreamReader(cs,Encoding.UTF8);
string result =sr.ReadToEnd();
return result;
}
}