简单的MD5密码加密和解密方法

来源:互联网 发布:二叉树层次遍历java 编辑:程序博客网 时间:2024/04/28 22:14

MD5的算法是不可逆的,MD5被广泛用于密码验证和消息体完整性验证。

下面的例子用到了密码加密和登陆时的解密的基本方法。当然这样很容易被暴力破解,可以做其他改进,如先设计一个足够复杂的密码,然后将他的MD5值与原密码MD5值相加后再求一次MD5值,这样可以增加破解难度。

简单示例如下:


        static void Main(string[] args)        {            Console.WriteLine("input password");            string source = Console.ReadLine();            string hash = GetMd5Hash(source);            Console.WriteLine("password: {0}, MD5 {1}", source, hash);            Console.WriteLine("input password");            string psd = Console.ReadLine();            if (VerifyMd5Hash(psd, hash))//验证成功返回OK                Console.WriteLine("OK");            else                Console.WriteLine("ERROR");            Console.ReadKey();        }        static string GetMd5Hash(string input)//获取密码对应的MD5字符串        {            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())            {                return BitConverter.ToString(md5.ComputeHash                    (UTF8Encoding.Default.GetBytes(input))).Replace("-", "");            }        }        static bool VerifyMd5Hash(string input, string Hash)//比较输入密码        {            string hashOfInput = GetMd5Hash(input);           // StringComparer comparer = StringComparer.OrdinalIgnoreCase;//忽略大小写的比较器            return hashOfInput.CompareTo(Hash) == 0 ? true : false;           // return comparer.Compare(hashOfInput, Hash) == 0 ? true : false;        }

0 0
原创粉丝点击