C# 中常用加密/解密方法

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

namespace Utility
{
    public class MD5Helper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="text">明文</param>
        /// <returns>密文</returns>
        public static string MD5Encryt(string text)
        {
            byte[] result = Encoding.Default.GetBytes(text.Trim());
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToUpper();
        }
    }
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Utility
{
    public class DESHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "szhtrfid");
        }

        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.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>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "zshtrfid");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
    }

    /// <summary>
    /// 采用 3重DES 加解密方式。
    /// </summary>
    public class TripleDESHelper
    {
        //   rgbKey:
        //     用于对称算法的密钥。
        //
        //   rgbIV:
        //     用于对称算法的初始化向量。
        static string strKey = "fdbc4y6hdhKlf4M3mjgGrMC3PbryXrxw";
        static string strIV = "RfnMfrpec48=";

        /// <summary>
        /// 默认加密字符串。 
        /// </summary>
        /// <param name="ConnString"></param>
        /// <returns></returns>
        public static string EncryptString(string encryptString)
        {
            if (string.IsNullOrWhiteSpace(encryptString)) return encryptString;

            return Convert.ToBase64String(TripleDESHelper.EncryptString(
                encryptString,
                Convert.FromBase64String(strKey),
                Convert.FromBase64String(strIV)
            )
            );
        }

        /// <summary>
        /// 默认解密字符串   
        /// </summary>
        /// <param name="EncryptedConnectionString"></param>
        /// <returns></returns>
        public static string DecrypteString(string EncryptedConnectionString)
        {
            if (string.IsNullOrWhiteSpace(EncryptedConnectionString)) return EncryptedConnectionString;

            return TripleDESHelper.DecrypteString(
                Convert.FromBase64String(EncryptedConnectionString),
                 Convert.FromBase64String(strKey),
                Convert.FromBase64String(strIV)
            ).TrimEnd('\0');
        }

        /// <summary>
        /// 使用指定的 Key 和 IV 加密 。 
        /// </summary>
        /// <param name="ToEncryptString"></param>
        /// <param name="byKey"></param>
        /// <param name="byIV"></param>
        /// <returns></returns>
        private static byte[] EncryptString(string ToEncryptString, byte[] byKey, byte[] byIV)
        {
            if (string.IsNullOrWhiteSpace(ToEncryptString))
                return null;

            MemoryStream memStm = new MemoryStream();
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            CryptoStream encStream = null;
            encStream = new CryptoStream(
               memStm, tdes.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write
               );

            byte[] byIn = Encoding.Default.GetBytes(ToEncryptString);
            encStream.Write(byIn, 0, byIn.Length);
            encStream.FlushFinalBlock();
            encStream.Close();
            return memStm.ToArray();
        }

        /// <summary>
        /// 使用指定的 Key 和 IV 解密。 
        /// </summary>
        /// <param name="byIn"></param>
        /// <param name="byKey"></param>
        /// <param name="byIV"></param>
        /// <returns></returns>
        private static string DecrypteString(byte[] byIn, byte[] byKey, byte[] byIV)
        {
            if (byIn == null || byIn.Length == 0) return string.Empty;

            MemoryStream memStm = new MemoryStream(byIn);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            CryptoStream encStream = new CryptoStream(
               memStm, tdes.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read
               );

            byte[] fromEncrypt = new byte[byIn.Length];
            encStream.Read(fromEncrypt, 0, fromEncrypt.Length);
            encStream.Close();

            string strRet = Encoding.Default.GetString(fromEncrypt);
            return strRet;
        }

        /// <summary>
        /// 获取随机(种子是 GUID 的 Byte 的和)长度的Byte数组.
        /// </summary>
        /// <param name="Len">要得到的数组的长度</param>
        /// <returns></returns>
        private static byte[] GetBytes(int Len)
        {
            int Seed = 0;
            byte[] bySeed = Guid.NewGuid().ToByteArray();

            foreach (byte byt in bySeed)
            {
                Seed += byt;
            }

            byte[] byKey = new byte[Len];
            new Random(Seed).NextBytes(byKey);
            return byKey;
        }

        /// <summary>
        /// 获取 Key 和 IV , 如果失败,返回null。 
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="IV"></param>
        public static void TryGetKeyAndIV(out byte[] Key, out byte[] IV)
        {
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            for (int i = 200; i > 0; i--)
            {
                try
                {
                    Key = GetBytes(i);
                    IV = GetBytes(i);
                    tdes.CreateDecryptor(Key, IV);
                    return;
                }
                catch { }
            }
            Key = null;
            IV = null;
            return;
        }
    }
}
using System;
using System.Security.Cryptography;
using System.Text;

namespace Utility
{
    public class AESHelper
    {
        private byte[] ivArray;
        private byte[] keyArray;

        public AESHelper(string key)
        {
            int num = 0x10;
            this.keyArray = Encoding.UTF8.GetBytes(key);
            this.ivArray = new byte[num];
            for (int i = 0; i < num; i++)
            {
                this.ivArray[i] = this.keyArray[i];
            }
        }

        public string Decrypt(string toDecrypt)
        {
            byte[] inputBuffer = Convert.FromBase64String(toDecrypt);
            RijndaelManaged managed = new RijndaelManaged
            {
                Key = this.keyArray,
                IV = this.ivArray,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };
            byte[] bytes = managed.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            return Encoding.UTF8.GetString(bytes);
        }

        public string Encrypt(string toEncrypt)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(toEncrypt);
            RijndaelManaged managed = new RijndaelManaged
            {
                Key = this.keyArray,
                IV = this.ivArray,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };
            byte[] inArray = managed.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
            return Convert.ToBase64String(inArray, 0, inArray.Length);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/hellowzl/p/9071604.html