欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net的DES加密和解密算法

程序员文章站 2024-03-13 22:51:58
...
/// <summary>
    /// DES(56位)
    /// DES算法为密码*中的对称密码*,又被成为美国数据加密标准,是1972年美国IBM公司研制的对称密码*加密算法。
    /// 其**长度为56位,明文按64位进行分组,将分组后的明文组和56位的**按位替代或交换的方法形成密文组的加密方法。
    /// </summary>
    public class DES
    {

        #region 公用des
        /// <summary>
        /// 改变**向量
        /// </summary>
        public void ChangeKeys()
        {
            Keys = PuKeys;
        }
        /// <summary>
        /// 改变**向量
        /// </summary>
        /// <param name="keys">自定义向量</param>
        public void ChangeKeys(byte[] keys)
        {
            if (keys.Length != 8)
            {
                throw new Exception("必须是8 为的 byte");
            }
            Keys = keys;
        }
      


        //默认**向量
        static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// 自定义公共
        /// </summary>
        public static byte[] PuKeys = { 0x15, 0x1, 0x0, 0x78, 0x91, 0xAD, 0x1D, 0xCF };

        /// <summary>
        /// 默认**
        /// </summary>
        static string okey = "CMDKDCJC";
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加***,要求为8位</param>
        public static string EncryptDES(string encryptString)
        {
            return EncryptDES(encryptString, okey);
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加***,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey,

rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解***,要求为8位,和加***相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string DecryptDES(string decryptString)
        {
            return DecryptDES(decryptString, okey);
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解***,要求为8位,和加***相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey,

rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        #endregion

        #region  
        /// <summary>
        ///  des解密方式
        /// </summary>
        /// <param name="mq">密文</param>
        /// <param name="Key">**</param>
        /// <param name="Vector"></param>
        /// <returns></returns>
        public static Byte[] Decrypt(String mq, String Key, String Vector)
        {

            Byte[] Data = Convert.FromBase64String(mq);
            Byte[] bKey = new Byte[8];
            bKey[0] = 82;
            bKey[1] = 82;
            bKey[2] = 79;
            bKey[3] = 70;
            bKey[4] = 79;
            bKey[5] = 84;
            bKey[6] = 79;
            bKey[7] = 69;

            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            Byte[] bVector = new Byte[8];
            bVector = bKey;
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
            Byte[] original = null;

            DESCryptoServiceProvider CryptoProvider = new DESCryptoServiceProvider();
            CryptoProvider.Mode = CipherMode.ECB;
            //CryptoProvider.Padding = PaddingMode.Zeros;

            try
            {

                // 开辟一块内存流,存储密文

                using (MemoryStream Memory = new MemoryStream(Data))
                {

                    // 把内存流对象包装成加密流对象

                    using (CryptoStream Decryptor = new CryptoStream(Memory,

                    CryptoProvider.CreateDecryptor(bKey, bVector),

                    CryptoStreamMode.Read))
                    {

                        // 明文存储区

                        using (MemoryStream originalMemory = new MemoryStream())
                        {

                            Byte[] Buffer = new Byte[1024];

                            Int32 readBytes = 0;

                            while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                            {

                                originalMemory.Write(Buffer, 0, readBytes);

                            }

                            original = originalMemory.ToArray();

                        }
                    }
                }
            }

            catch(Exception e)
            {
                original = null;

            }
            return original;

        }


      

        /// <summary>
        ///  DES加密方法
        /// </summary>
        /// <param name="strPlain">明文</param>
        /// <param name="strDESKey">**</param>
        /// <param name="strDESIV">向量</param>
        /// <returns>密文</returns>
        public static string DESEncrypt(string strPlain, string strDESKey, string strDESIV)
        {

            Byte[] bytesDESKey = new Byte[8];
            bytesDESKey[0] = 82;
            bytesDESKey[1] = 82;
            bytesDESKey[2] = 79;
            bytesDESKey[3] = 70;
            bytesDESKey[4] = 79;
            bytesDESKey[5] = 84;
            bytesDESKey[6] = 79;
            bytesDESKey[7] = 69;
            Array.Copy(Encoding.UTF8.GetBytes(strDESKey.PadRight(bytesDESKey.Length)), bytesDESKey, bytesDESKey.Length);
            Byte[] bytesDESIV = new Byte[8];
            bytesDESIV = bytesDESKey;
            Array.Copy(Encoding.UTF8.GetBytes(strDESIV.PadRight(bytesDESIV.Length)), bytesDESIV, bytesDESIV.Length);


            //声明1个新的DES对象
            DESCryptoServiceProvider desEncrypt = new DESCryptoServiceProvider();
            desEncrypt.Mode = CipherMode.ECB;
            //desEncrypt.Padding = PaddingMode.Zeros;

            //开辟一块内存流
            MemoryStream msEncrypt = new MemoryStream();
            //把内存流对象包装成加密流对象
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, desEncrypt.CreateEncryptor(bytesDESKey, bytesDESIV), CryptoStreamMode.Write);
            byte[] inputByteArray = Encoding.UTF8.GetBytes(strPlain);
            csEncrypt.Write(inputByteArray, 0, inputByteArray.Length);
            csEncrypt.FlushFinalBlock();
            return Convert.ToBase64String(msEncrypt.ToArray());
        }


        #endregion

        #region MD5
        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            StringBuilder ret = new StringBuilder();
            for (int i = 0; i < b.Length; i++)
                ret.Append(b[i].ToString("x").PadLeft(2, '0'));
            return ret.ToString();
        }

        public static string GMD5(string message)
        {
            Byte[] clearBytes = new UnicodeEncoding().GetBytes(message);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

            String tt = BitConverter.ToString(hashedBytes).Replace("-", "");
            // MessageBox.Show(tt.Length.ToString());
            return tt;

        }


        public static string ToGB2312(string str)
        {
            string r = "";
            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            byte[] bts = new byte[2];
            foreach (System.Text.RegularExpressions.Match m in mc)
            {
                bts[0] = (byte)int.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
                r += Encoding.Unicode.GetString(bts);
            }
            return r;
        }