【C#】整理综合C#加密解密类

整理发布之前的【Update】对之前的AES-256加密软件进行版本更新所使用的加密类……

本来由于这个是使用于网络上已有的代码所整合而成的一个加密类,但是昨天有网友留言问能不能发份源码给他,想着反正都是整理于网络上的对于我来说没有版权,于是就把整合的加密类帖出来算了。

再这里就唠叨一句,由于之前没有学习到相关的内容,但是我在一C#的桌面应用程序的项目答辩中为了使用MD5加密用户的密码也上网搜索了相关加密方法来进行加密。虽然现在不知道什么原因就没有学这本书后面几章了,但是这本ASP.NET的书中后面有个关于《用户密码加密》的章节中讲到:

1.MD5类在System.Security.Cryptography命名空间中
2.使用MD5类的ComputeHash()方法进行加密,注意:此方法的参数和返回值均为byte[]类型
3.可以使用FormsAuthention.HashPasswordForStoringlnConfigFile()方法替代MD5类的ComputeHash()方法用来加密字符串。FormsAuthention类在System.Web.Security命名空间中。
//我注:FormsAuthention.HashPasswordForStoringlnConfigFile()方法在VS中提示该方法已经过时。

所以可以说可以直接使用了咯。虽然我使用别人自定义的那个MD5加密类有自己加入的字段来使其比普通的更安全一丢丢。
命名空间

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

以下代码搜集于网络

    ///<summary>
    ///DES
    ///</summary>
    class DesEncryptDecryptHelper {
        ///<summary>
        ///DES
        ///</summary>
        /// <param name="pToEncrypt">DES Text</param>
        /// <param name="sKey">DES Key</param>
        /// <returns></returns>
        //DES加密   
        public static string DesEncrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            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);
            }
            ret.ToString();
            return ret.ToString();


        }

        ///<summary>
        ///DES
        ///</summary>
        /// <param name="pToDecrypt">DES Text</param>
        /// <param name="sKey">DES Key</param>
        /// <returns></returns>
        //解密
        public static string DesDecrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
    }
    ///<summary>
    ///AES
    ///</summary>
    class AesEncryptDecryptHelper
    {
        ///<summary>
        ///AES加密
        ///</summary>
        /// <param name="toEncrypt">AES Text</param>
        /// <returns></returns>

        public static string aeskey = "";  //默认密匙(32位十六进制字符)
        //加密函数
        public static string AesEncrypt(string toEncrypt)
        {
            // 256-AES key    
            
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(aeskey);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

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

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

        /// <summary>
        /// AES
        /// </summary>
        /// <param name="toDecrypt">AES Text</param>
        /// <returns></returns>
        //解密函数

        public static string  AesDecrypt(string toDecrypt)
        {
            // 256-AES key  
            
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(aeskey);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        /// <summary>
        /// AES key
        /// </summary>
        /// <param name="key">AES Key</param>
        
    }


    /// <summary>
    /// Rsa
    /// </summary>
    class RsaEncryptDecryptHelper {
        #region 默认密钥向量
        //默认密钥向量 
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        #endregion


        #region 利用MD5对字符串进行加密
        ///   <summary> 
        ///   利用MD5对字符串进行加密 
        ///   </summary>
        ///   <param name= "encryptString "> 待加密的字符串 </param> 
        ///   <returns> 返回加密后的字符串 </returns> 
        public static string EncryptMD5(string encryptString)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            UTF8Encoding Encode = new UTF8Encoding();
            byte[] HashedBytes = md5Hasher.ComputeHash(Encode.GetBytes(encryptString));
            return Encode.GetString(HashedBytes);
        }
        #endregion


        #region RSA


        #region rsa解密
        /// <summary>
        /// rsa解密
        /// </summary>
        /// <param name="s">加密后字符串字符串</param>
        /// <param name="key">加密key</param>
        /// <returns></returns>
        public static string RSADecrypt(string s, string key)
        {
            string result = null;
            if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
            if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = key;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
            rsa.PersistKeyInCsp = true;
            string[] decryptArray = s.Split(new string[] { "-" }, StringSplitOptions.None);
            byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (a => Convert.ToByte(byte.Parse(a, System.Globalization.NumberStyles.HexNumber))));
            byte[] bytes = rsa.Decrypt(decryptByteArray, true);
            result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
            return result;
        }
        #endregion


        #region rsa加密
        /// <summary>
        /// rsa加密
        /// </summary>
        /// <param name="s">要加密的字符串</param>
        /// <param name="key">加密key</param>
        /// <returns></returns>
        public static string RSAEncrypt(string s, string key)
        {
            if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
            if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = key;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
            rsa.PersistKeyInCsp = true;
            byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(s), true);
            return BitConverter.ToString(bytes);
        }
        #endregion
        #endregion
    }

    /// <summary>
    /// 3DES-1
    /// </summary>
    class DES31EncryptDecryptHelper
    {
        #region 3DES-1


        #region 3DES加密
        /// <summary>
        /// 3DES加密
        /// </summary>
        /// <param name="strString">需要加密的字符串</param>
        /// <param name="strKey">加密key</param>
        /// <returns></returns>
        public static string DES3Encrypt(string strString, string strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();


            DES.Key = hashMD5.ComputeHash(Encoding.Default.GetBytes(strKey));
            DES.Mode = CipherMode.ECB;


            ICryptoTransform DESEncrypt = DES.CreateEncryptor();


            byte[] Buffer = Encoding.Default.GetBytes(strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        #endregion


        #region 3DES解密
        /// <summary>
        /// 3DES解密
        /// </summary>
        /// <param name="strString">解密字符串</param>
        /// <param name="strKey">解密key</param>
        /// <returns></returns>
        public static string DES3Decrypt(string strString, string strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();


            DES.Key = hashMD5.ComputeHash(Encoding.Default.GetBytes(strKey)); DES.Mode = CipherMode.ECB;
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(strString);
                result = Encoding.Default.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (System.Exception e)
            {
                throw (new System.Exception("null", e));
            }
            return result;
        }
        #endregion

        #endregion
    }



    /// <summary>
    /// RC2
    /// </summary>
    class RC2EncryptDecryptHelper
    {
        #region RC2


        #region RC2加密
        /// <summary>
        /// RC2加密
        /// </summary>
        /// <param name="encryptString">待加密的密文</param>
        /// <param name="encryptKey">密匙(必须为5-16位)</param>
        /// <returns></returns>
        public static string RC2Encrypt(string encryptString, string encryptKey)
        {
            string returnValue;
            try
            {
                byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider();
                byte[] byteEncryptString = Encoding.Default.GetBytes(encryptString);
                MemoryStream memorystream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memorystream, rC2.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), temp), CryptoStreamMode.Write);
                cryptoStream.Write(byteEncryptString, 0, byteEncryptString.Length);
                cryptoStream.FlushFinalBlock();
                returnValue = Convert.ToBase64String(memorystream.ToArray());


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnValue;


        }
        #endregion


        #region RC2解密
        /// <summary>
        /// RC2解密
        /// </summary>
        /// <param name="decryptString">密文</param>
        /// <param name="decryptKey">密匙(必须为5-16位)</param>
        /// <returns></returns>
        public static string RC2Decrypt(string decryptString, string decryptKey)
        {
            string returnValue;
            try
            {
                byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider();
                byte[] byteDecrytString = Convert.FromBase64String(decryptString);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, rC2.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), temp), CryptoStreamMode.Write);
                cryptoStream.Write(byteDecrytString, 0, byteDecrytString.Length);
                cryptoStream.FlushFinalBlock();
                returnValue = Encoding.Default.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnValue;
        }
        #endregion


        #endregion
    }


    /// <summary>
    /// 3DES-2
    /// </summary>
    class DES32EncryptDecryptHelper
    {
        #region 3DES-2


        #region 3DES 加密
        /// <summary>
        /// 3DES 加密
        /// </summary>
        /// <param name="encryptString">待加密密文</param>
        /// <param name="encryptKey1">密匙1(长度必须为8位)</param>
        /// <param name="encryptKey2">密匙2(长度必须为8位)</param>
        /// <param name="encryptKey3">密匙3(长度必须为8位)</param>
        /// <returns></returns>
        public static string DES3Encrypt(string encryptString, string encryptKey1, string encryptKey2, string encryptKey3)
        {


            string returnValue;
            try
            {
                returnValue = DES31EncryptDecryptHelper.DES3Encrypt(encryptString, encryptKey3);
                returnValue = DES31EncryptDecryptHelper.DES3Encrypt(returnValue, encryptKey2);
                returnValue = DES31EncryptDecryptHelper.DES3Encrypt(returnValue, encryptKey1);


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnValue;


        }
        #endregion


        #region 3DES 解密
        /// <summary>
        /// 3DES 解密
        /// </summary>
        /// <param name="decryptString">待解密密文</param>
        /// <param name="decryptKey1">密匙1(长度必须为8位)</param>
        /// <param name="decryptKey2">密匙2(长度必须为8位)</param>
        /// <param name="decryptKey3">密匙3(长度必须为8位)</param>
        /// <returns></returns>
        public static string DES3Decrypt(string decryptString, string decryptKey1, string decryptKey2, string decryptKey3)
        {


            string returnValue;
            try
            {
                returnValue = DES31EncryptDecryptHelper.DES3Decrypt(decryptString, decryptKey1);
                returnValue = DES31EncryptDecryptHelper.DES3Decrypt(returnValue, decryptKey2);
                returnValue = DES31EncryptDecryptHelper.DES3Decrypt(returnValue, decryptKey3);


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnValue;
        }
        #endregion


        #endregion
    }

收集整理

超越自我吧
2017年1月4日

发布者

ChiuYut

咦?我是谁?这是什么地方? Ya ha!我是ChiuYut!这里是我的小破站!