Asp.Net 常用工具类之加密——对称加密DES算法(2)

  

 

  又到周末,下午博客园看了两篇文章,关于老跳和老赵的程序员生涯,不禁感叹漫漫程序路,何去何从兮!

  转眼毕业的第三个年头,去过苏州,跑过上海,从一开始的凌云壮志,去年背起行囊默默回到了长沙准备买房,也想有个家(毕竟年级不小了),有盼头的工作前景。

  看到老赵和老跳两位前辈的故事,真实且现实,同时也有一丢丢的小迷茫,敢问路在何方!


  感叹一会儿,生命不止,Code不止,继续入坑!

  昨天分享了一下非对称加密RSA算法,今天给朋友们分享一下对称加密DES算法案例。

  加解密过程:

  1、生成加密密钥key,密码越长,越难破解,穷举太累

  2、加密:通过等分、移位、选取和迭代形成一套16个加密密钥,分别供每一轮运算中使用

  3、解密:解密密钥的次序相反

  上述我理解的DES加解密过程,当然咯,这里涉及到密码安全学,本人涉及粗浅。详情百度《DES加密算法原理》。

  C#中大多加解密算法都集中在 System.Security.Cryptography 空间,谨记。

  下面通过一个案例给大家展示一下:

using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Utils.PassWord
{
    /// <summary>
    /// DES加解密
    /// </summary>
    public static class DES
    {
        /// <summary>
        /// 生成key
        /// </summary>
        public static void Generator(out string key)
        {
            DESCryptoServiceProvider des = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            key = ASCIIEncoding.ASCII.GetString(des.Key);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="password"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESEncrypt(string password, string key)
        {
            byte[] data = Encoding.UTF8.GetBytes(password);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
            ICryptoTransform desEncrypt = DES.CreateEncryptor();
            byte[] result = desEncrypt.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(result);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="password"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DESDecrypt(string password, string key)
        {
            string[] sinput = password.Split("-".ToCharArray());
            byte[] data = new byte[sinput.Length];
            for (int i = 0; i < sinput.Length; i++)
            {
                data[i] = byte.Parse(sinput[i], NumberStyles.HexNumber);
            }
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
            ICryptoTransform desencrypt = DES.CreateDecryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Encoding.UTF8.GetString(result);
        }

        /// <summary>   
        /// 加密数据   MD5方式
        /// </summary>   
        /// <param name="str"></param>   
        /// <param name="key">加密密钥</param>   
        /// <returns></returns>   
        public static string DESEncryptMD5(string str, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(str); 
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
                ret.AppendFormat("{0:X2}", b);
            return ret.ToString();
        }

        /// <summary>   
        /// 解密数据   MD5方式
        /// </summary>   
        /// <param name="str"></param>   
        /// <param name="key">加密密钥</param>   
        /// <returns></returns>   
        public static string DESDecryptMD5(string str, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = str.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(str.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            MemoryStream ms = new  MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
    } 
}

调用方式

public static void des()
{
    string key = "";
    DES.Generator(out key);
    var aaa = DES.DESEncryptMD5("123456789", "12312312");
    var bbb = DES.DESDecryptMD5(aaa, "12312312");
    var cc = DES.DESEncrypt("123456789", key);
    var dd = DES.DESDecrypt(cc, key);
}

 

 

 

OK,各位看官,这一期的文章对称加密DES算法写到这里喏,感谢大家的支持,您的支持是我的动力!

下一期给大家带来的是加密可逆与不可逆的几种方式,敬请期待!!!

posted on 2017-03-04 17:33  黑马狼  阅读(2218)  评论(1编辑  收藏  举报

导航