• MD5加密


      MD5是一种散列函数算法,用MD5进行的加密不可逆,所以是一种常用的安全的加密方法。

    MD5加密步骤

    1.得到要加密数据的字节流

     1)如果是文件直接得到文件流

     2)如果是字符串,使用Encoding

    2.创建MD5对象

    3.调用其computeHash方法,将字节流作为参数,返回长度为16的字节流

    4.将byte[16]变成字符串

     1)将每一个字节用两个十六进制数显式出来
     2)利用for循环得到每一个字节
     3)使用ToString("x2")方法(ToString(“x2”)目的是获取两位16进制数)

    示例代码:

    两个命名空间:

    MD5:using System.Security.Cryptography

    Encoding:using System.Text

           static void Main(string[] args)
            {
                string pwd = "wangyixuan";
                string md5pwd = GetMD5(pwd );
                Console.WriteLine(md5pwd );
                Console.ReadKey();
            }
            static string GetMD5(string str)
            {
    
                byte[] oldStr = Encoding.GetEncoding("gb2312").GetBytes(str );//1.获取字节流
                StringBuilder sb = new System.Text.StringBuilder();
                using (MD5 md5 = MD5.Create())//2.创建MD5对象  或使用MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                {
    byte[] b =md5 .ComputeHash (oldStr );//3.得到长度为16的字节流 for (int i = 0; i < b.Length ; i++) { sb.Append(b[i].ToString("x2"));//4.将字节流变成字符串 } } return sb.ToString(); }

    方法二

                string pwd = "wangyixuan";
                byte[] bStart = Encoding.Default.GetBytes(pwd);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] bEnd = md5.ComputeHash(bStart);
                string result = BitConverter.ToString(bEnd);
                Console.WriteLine(result );

    方法三:在ASP.net中的MD5加密,命名空间:using System.Web.Security

    public static string Md5(string str, int code)
        {
            //str = System.Web.HttpUtility.UrlEncode(str);   
            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();
            }
        }
  • 相关阅读:
    lodash chunk
    lodash.slice
    ⚡ vue3 全家桶体验
    构建一个简约博皮的过程
    [译] 制作 Vue 3 的过程
    ⚠ | 不要再使用 markdown 主题了!
    win 常用命令
    2020年了,别再重复学习原型了
    删除 linux 导致原来的 win10 进不去
    手写一个文章目录插件
  • 原文地址:https://www.cnblogs.com/wangliu/p/3751450.html
Copyright © 2020-2023  润新知