潜移默化学会WPF(安全篇<一>)--MD5加密三种方法加实践

一、MD5潜移默化公式

     

System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(   你要加密的string字符串 , "MD5");//密码加密

备注:MD5你可以换成SHA1  就是SHA1加密了,前提是你要引入  System.Web.dll  类库

MS SQL和MySQL的MD5加密
MS SQL:
SELECT SUBSTRING(SYS.FN_VARBINTOHEXSTR(HASHBYTES('MD5','123456')),11,16) --换成32就是32位的

MY SQL:直接SELECT MD5('123456')

实践一下

public static string md5(string str,int code) 
{
if(code==16) //16位MD5加密(取32位加密的9~25字符)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ;
}
else //32位加密
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower();
}
}
使用该函数加密,str是原始字符串,函数返回加密后的字符串
插入数据用ADO.NET

 

另一个我是自己写好了个类 ,自己引进去就可以用了(你可以自由发挥哦,中间你可以加任何你想加的东东)

 

MD5加密 源写法
using System;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.IO;

namespace CommonUtility.Cryptography
{
/// <summary>
/// MD5加密类,注意经MD5加密过的信息是不能转换回原始数据的
/// ,请不要在用户敏感的信息中使用此加密技术,比如用户的密码,
/// 请尽量使用对称加密
/// </summary>
public class MD5Encrypt
{
private MD5 md5;
/// <summary>
/// 构造函数
/// </summary>
public MD5Encrypt()
{
md5 = new MD5CryptoServiceProvider();
}
/// <summary>
/// 从字符串中获取散列值
/// </summary>
/// <param name="str">要计算散列值的字符串</param>
/// <returns></returns>
public string GetMD5FromString(string str)
{
byte[] toCompute = Encoding.Unicode.GetBytes(str);
byte[] hashed = md5.ComputeHash(toCompute, 0, toCompute.Length);
return Encoding.ASCII.GetString(hashed);
}
/// <summary>
/// 根据文件来计算散列值
/// </summary>
/// <param name="filePath">要计算散列值的文件路径</param>
/// <returns></returns>
public string GetMD5FromFile(string filePath)
{
bool isExist = File.Exists(filePath);
if (isExist)//如果文件存在
{
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream, Encoding.Unicode);
string str = reader.ReadToEnd();
byte[] toHash = Encoding.Unicode.GetBytes(str);
byte[] hashed = md5.ComputeHash(toHash, 0, toHash.Length);
stream.Close();
return Encoding.ASCII.GetString(hashed);
}
else//文件不存在
{
throw new FileNotFoundException("File not found!");
}
}
}
}


先不写了,没评论没动力

posted @ 2012-04-07 14:52  AYUI框架  阅读(1129)  评论(1编辑  收藏  举报