C#加密SecurityHelper

接下来给大家分享一下我用的加密helper,现在只用的md5加密的方法,网上很多方法找到的时候加密完了会变成乱码,这样对于密码这种字段保存的时候就会出错。其实只需要把加密完的byte字节转化成16位就可以了。

ps:

昨天写的把最后转换成的byte转换为十六进制的数是用的方法是tostring(“X”),今天在写登录的模块的时候发现和MD5.js转化出来的字符串不一致,具体就是tostring(“X”)没有补齐位数,而MD5.js是补齐了位数的,所以要用tostring(“X2”)这个方法,补齐两位,就能一致了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CodeHelper
{
    public class SecurityHelper
    {
        ///   <summary>
        ///   给一个字符串进行MD5加密
        ///   </summary>
        ///   <param   name="strText">待加密字符串</param>
        ///   <returns>加密后的字符串</returns>
        public static string MD5Encrypt(string strText)
        {
            string encryptPwd = "";
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashPwd = md5.ComputeHash(Encoding.UTF8.GetBytes(strText));
            foreach (byte b in hashPwd)
            {
                encryptPwd += b.ToString("X2");//转换成十六进制数,不然返回的字符串可能是乱码
            }

            return encryptPwd;
        }
    }
}
原文地址:https://www.cnblogs.com/junshijie/p/6526884.html