首页 > 代码库 > .Net 加密 哈希

.Net 加密 哈希

一、DES加解密

  DES一共就有4个参数参与运作:明文、密文、密钥、向量。其中这4者的关系可以理解为:

  •   密文=明文+密钥+向量;
  •   明文=密文-密钥-向量;

  为什么要向量这个参数呢?因为如果有一篇文章,有几个词重复,那么这个词加上密钥形成的密文,仍然会重复,这给破解者有机可乘,破解者可以根据重复的内容,猜出是什么词,然而一旦猜对这个词,那么,他就能算出密钥,整篇文章就被破解了!加上向量这个参数以后,每块文字段都会依次加上一段值,这样,即使相同的文字,加密出来的密文,也是不一样的,算法的安全性大大提高!

  下面给出DES加、解密的.Net封装版:

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

namespace 开发测试
{
    class Program
    {
        static void Main(string[] args)
        {
            string user = Encrypt("admin");
            string pass = Encrypt("999999");

            Console.WriteLine(user);
            Console.WriteLine(pass);

            string GetUser = Decrypt(user);
            string GetPass = Decrypt(pass);

            Console.WriteLine(GetUser);
            Console.WriteLine(GetPass);

            Console.ReadLine();
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        private static string Key
        {
            get { return @"P@+#wG%A"; }
        }

        /// <summary>
        /// 获取向量
        /// </summary>
        private static string IV
        {
            get { return @"L*n67}G\Mk@k%:~Y"; }
        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <returns>密文</returns>
        public static string Encrypt(string plainStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();
            return encrypt;
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encryptStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();
            return decrypt;
        }
    }
}

 

二、AES加解密

  AES是美国联邦政府采用的商业及政府数据加密标准,预计将在未来几十年里代替DES在各个领域中得到广泛应用。AES提供128位密钥,因此,128位AES的加密强度是56位DES加密强度的1021倍还多。假设可以制造一部可以在1秒内破解DES密码的机器,那么使用这台机器破解一个128位AES密码需要大约149亿万年的时间。

  下面给出AES加解密的.Net封装版:

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

namespace 开发测试
{
    class Program
    {
        static void Main(string[] args)
        {
            string user = Encrypt("admin");
            string pass = Encrypt("999999");

            Console.WriteLine(user);
            Console.WriteLine(pass);

            string GetUser = Decrypt(user);
            string GetPass = Decrypt(pass);

            Console.WriteLine(GetUser);
            Console.WriteLine(GetPass);

            Console.ReadLine();
        }


        /// <summary>
        /// 获取密钥
        /// </summary>
        private static string Key
        {
            get { return @"qO[NB]6,YF}gefcaj{+oESb9d8>Z‘e9M"; }
        }

        /// <summary>
        /// 获取向量
        /// </summary>
        private static string IV
        {

            get { return @"L+\~f4.Ir)b$=pkf"; }
        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <returns>密文</returns>
        public static string Encrypt(string plainStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            Rijndael aes = Rijndael.Create();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            aes.Clear();

            return encrypt;
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encryptStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            Rijndael aes = Rijndael.Create();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            aes.Clear();

            return decrypt;
        }
    }
}

三、MD5与SHA128、256...散列

  MD5和SHA1散列通常被用于密码中,很多人称其为散列算法,实际上它正确应该叫做散列算法。散列是不可逆的,也就是没有了"解密"这个说法。

  下面给出MD5与SHA128散列的.Net的System.Web快速实现版:

using System;
using System.Text;
using System.IO;

namespace 开发测试
{
    class Program
    {
        static void Main(string[] args)
        {
            string user = MD5("admin");
            string pass = MD5("999999");

            Console.WriteLine(user);
            Console.WriteLine(pass);

            string user2 = SHA1("admin");
            string pass2 = SHA1("999999");

            Console.WriteLine(user2);
            Console.WriteLine(pass2);

            Console.ReadLine();
        }

        //32位大写MD5散列
        public static string MD5(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToUpper();
        }

        //大写SHA1散列
        public static string SHA1(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1").ToUpper();
        }
    }
}

  全面版:

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

namespace 开发测试
{
    class Program
    {
        static void Main(string[] args)
        {
            string user = MD5("admin");
            string pass = MD5("999999");

            Console.WriteLine(user);
            Console.WriteLine(pass);

            string user2 = SHA128("admin");
            string pass2 = SHA128("999999");

            Console.WriteLine(user2);
            Console.WriteLine(pass2);

            string user3 = SHA256("admin");
            string pass3 = SHA256("999999");

            Console.WriteLine(user3);
            Console.WriteLine(pass3);

            string user4 = SHA384("admin");
            string pass4 = SHA384("999999");

            Console.WriteLine(user4);
            Console.WriteLine(pass4);

            string user5 = SHA512("admin");
            string pass5 = SHA512("999999");

            Console.WriteLine(user5);
            Console.WriteLine(pass5);

            Console.ReadLine();
        }

        //16字节,128位
        public static string MD5(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
            byte[] byteArr = MD5.ComputeHash(buffer);
            return BitConverter.ToString(byteArr);
        }


        //20字节,160位
        public static string SHA128(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
            byte[] byteArr = SHA1.ComputeHash(buffer);
            return BitConverter.ToString(byteArr);
        }


        //32字节,256位
        public static string SHA256(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider();
            byte[] byteArr = SHA256.ComputeHash(buffer);
            return BitConverter.ToString(byteArr);
        }


        //48字节,384位
        public static string SHA384(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            SHA384CryptoServiceProvider SHA384 = new SHA384CryptoServiceProvider();
            byte[] byteArr = SHA384.ComputeHash(buffer);
            return BitConverter.ToString(byteArr);
        }

        //64字节,512位
        public static string SHA512(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            SHA512CryptoServiceProvider SHA512 = new SHA512CryptoServiceProvider();
            byte[] byteArr = SHA512.ComputeHash(buffer);
            return BitConverter.ToString(byteArr);
        }
    }
}