c#中的MD5加密字符串和加密文件

来源:互联网 发布:柯蓝 知乎 编辑:程序博客网 时间:2024/05/18 01:07

在实际的工作当时,不乏字符串的加密处理,例如悲催的csdn密码泄漏,只因该系统把用户的密码以明文的方式在数据库中进行保存,如果把用户的密码经md5处理后,即使管理员登录数据库也不能识别出用户的密码,在安全方面则做到了保密。

一般md5加密,分为字符串加密和文件加密两种。这里说的加密只是一种不严谨的说法,实际并非加密,只是一种散列算法,其不可逆,即拿到一个md5值不能反向得到源字符串或源文件内容,如果能够可逆,试想当我们得到一个md5值后就可以得反向得到一个1T大的蓝光高清电影,这是多么恐怖的事情。

 

 

#region 1.获得md5值        public static string GetMD5(string msg)        {            StringBuilder sb = new StringBuilder();            using (MD5 md5=MD5.Create())            {                byte[] buffer = Encoding.UTF8.GetBytes(msg);                byte[] newB = md5.ComputeHash(buffer);                foreach (byte item in newB)                {                    sb.Append(item.ToString("x2"));                }            }            return sb.ToString();        }        #endregion


#region 2获得一个文件的MD5        public static string GetFileMD5(string filepath)        {            StringBuilder sb = new StringBuilder();            using (MD5 md5=MD5.Create())            {                using (FileStream fs=File.OpenRead(filepath))                {                    byte[] newB = md5.ComputeHash(fs);                    foreach (byte item in newB)                    {                        sb.Append(item.ToString("x2"));                    }                }            }            return sb.ToString();        }        #endregion


原创粉丝点击