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

C# DES加解密

程序员文章站 2024-03-14 11:02:28
...
        /// <summary>
        /// TripleDES 加密
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string DesEncrypt(string toEncrypt, byte[] privateKey)
        {
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider
            {
                Key = privateKey,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// TripleDES解密
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string DesDecrypt(string toDecrypt, byte[] privateKey)
        {
            string res = "";
            try
            {
                //先base64解密 因为加密的时候最后走了一道base64加密
                byte[] enBytes = Convert.FromBase64String(toDecrypt);
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider
                {
                    Key = privateKey,
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };

                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(enBytes, 0, enBytes.Length);
                tdes.Clear();
                res = Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception e)
            {
                Console.WriteLine("解密失败:" + e.Message);
            }
            return res;
        }


        /// <summary>
        /// 获取加密key的 md5 hash,最终DES加密的时候使用这个hash值
        /// </summary>
        /// <param name="key">原始key值</param>
        /// <returns></returns>
        public static byte[] GetKeyMd5Hash(string key)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            byte[] keyBytes = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();

            return keyBytes;
        }

//加密

string res = DesEncrypt("明文", Tool.GetKeyMd5Hash("秘钥"));

//解密:

string res = DesDecrypt("密文", Tool.GetKeyMd5Hash("秘钥"));