C# 生成MD5编码方法(不同位数)

本文介绍了如何使用MD5算法对字符串进行加密,并提供了两种不同长度(16位和32位)的加密方法。通过.NET Framework提供的CryptoConfig类创建MD5实例完成加密过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        /// <summary> 
        /// </summary> 
        /// <param name="strSource">待加密字串</param> 
        /// <returns>加密后的字串</returns> 
        public static string MD5Encrypt(string strSource)
        {
            return MD5Encrypt(strSource, 32);
        }

        /// <summary> 
        /// </summary> 
        /// <param name="strSource">待加密字串</param> 
        /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param> 
        /// <returns>加密后的字串</returns> 
        public static string MD5Encrypt(string strSource, int length)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(strSource);
            byte[] hashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            switch (length)
            {
                case 16:
                    for (int i = 4; i < 12; i++)
                        sb.Append(hashValue[i].ToString("x2"));
                    break;
                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                default:
                    for (int i = 0; i < hashValue.Length; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
            }
            return sb.ToString();
        } 

转载于:https://www.cnblogs.com/houzuofeng/p/3253187.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值