C#加密常用類

 C#加密常用類

 

1.常用的類有如下:
(1).对称加密
DESCryptoServiceProvider
RC2CryptoServiceProvider
RijndaelManaged
ripleDESCryptoServiceProvider

(2).非對稱加密
DSACryptoServiceProvider
RSACryptoServiceProvider

(3).數字簽名
DSACryptoServiceProvider
RSACryptoServiceProvider

2.類的使用
    public class FileSecurity
    {

        #region md5
        /// <summary>
        /// MD5 16位加密
        /// </summary>
        /// <param name="convertString"></param>
        /// <returns></returns>
        public static string Md5Encrypt16(string convertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            //??成字符串,并取9到25位
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(convertString)), 4, 8);
            //BitConverter轉換出來的字符串會在每個字符中間產生一個分隔符,需要去除掉
            t2 = t2.Replace("-", "");
            return t2;
        }

        /// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="convertString"></param>
        /// <returns></returns>
        public static string Md5Encrypt32(string convertString)
        {
            string pwd = "";
            MD5 md5 = MD5.Create();
            //注意編碼UTF8、UTF7、Unicode等的選擇
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(convertString));
            //將字節類型的數組轉換為字符串,此字符串是常規字符格式化所得 
            for (int i = 0; i < s.Length; i++)
            {
                //將得到的字符串使用16進製類型格式,格式後的字符是小寫的字母,如果使用大寫(X)則格式後的字符是大寫字符
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }

        #endregion

        #region DES
        /// <summary>
        /// 文件加密
        /// </summary>
        /// <param name="inName">源文件路徑</param>
        /// <param name="outName">輸出文件路徑</param>
        /// <param name="desKey"></param>
        /// <param name="desIV"></param>
        /// <returns>轉換成功則為true</returns>
        public static bool DESEncrypt(string inName, string outName, byte[] desKey, byte[] desIV)
        {
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);
            byte[] bin = new byte[100];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;
            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
            }
            encStream.Close();
            fout.Close();
            fin.Close();
            return true;
        }

        /// <summary>
        /// 文件解密
        /// </summary>
        /// <param name="inName">源文件路徑</param>
        /// <param name="outName">輸出文件路徑</param>
        /// <param name="desKey"></param>
        /// <param name="desIV"></param>
        /// <returns></returns>
        public static bool DESDecrypt(string inName, string outName, byte[] desKey, byte[] desIV)
        {
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);
            byte[] bin = new byte[100];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;
            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
            }
            encStream.Close();
            fout.Close();
            fin.Close();
            return true;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="datastr">要加密的字符串</param>
        /// <param name="keystr">加密密鑰</param>
        /// <returns>加密后的字符串</returns>
        public static string DESEncrypt(string datastr, string keystr)
        {
            DESCryptoServiceProvider desc = new DESCryptoServiceProvider();

            byte[] key = System.Text.Encoding.ASCII.GetBytes(keystr);
            byte[] data = System.Text.Encoding.Unicode.GetBytes(datastr);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);

            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();

            return System.Convert.ToBase64String(ms.ToArray());

        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="datastr">要解密的字符串</param>
        /// <param name="keystr">解密的密鑰</param>
        /// <returns></returns>
        public static string DESDecrypt(string datastr, string keystr)
        {
            byte[] data = System.Convert.FromBase64String(datastr);

            DESCryptoServiceProvider desc = new DESCryptoServiceProvider();

            byte[] key = System.Text.Encoding.ASCII.GetBytes(keystr);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);

            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();

            return System.Text.Encoding.Unicode.GetString(ms.ToArray());
        }

        #endregion

        #region RC2
        //kes與iv的長度相等
        //private static Byte[] Keys = System.Text.Encoding.Unicode.GetBytes("天天向上");
        //private static Byte[] IV = new Byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };


        /// <summary>
        /// 加密,kes與iv的長度相等
        /// </summary>
        /// <param name="str"></param>
        /// <param name="keys"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static Byte[] RC2Encrypt(String str, Byte[] keys, byte[] iv)
        {
            System.Security.Cryptography.RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
            MemoryStream msStream = new MemoryStream();
            byte[] toEncrypt;

            ICryptoTransform encrypt = rc2.CreateEncryptor(keys, iv);
            CryptoStream csStream = new CryptoStream(msStream, encrypt, CryptoStreamMode.Write);

            toEncrypt = System.Text.Encoding.Unicode.GetBytes(str);
            csStream.Write(toEncrypt, 0, toEncrypt.Length);
            csStream.FlushFinalBlock();
            return msStream.ToArray();
        }

        /// <summary>
        /// 解密,kes與iv的長度相等
        /// </summary>
        public static String RC2Decrypt(Byte[] enc, Byte[] keys, byte[] iv)
        {
            System.Security.Cryptography.RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
            ICryptoTransform decrypt = rc2.CreateDecryptor(keys, iv);
            MemoryStream msDec = new MemoryStream(enc);
            CryptoStream csDec = new CryptoStream(msDec, decrypt, CryptoStreamMode.Read);
            byte[] fromEncpty = new Byte[enc.Length];
            csDec.Read(fromEncpty, 0, fromEncpty.Length);
            return System.Text.Encoding.Unicode.GetString(fromEncpty);
        }

        #endregion

        #region RSA
        //a.加密(用對方公鑰)  
        //b.數字簽名(用自己私鑰)  
        //c.解密(自己私鑰)  
        //d.驗證簽名(對方公鑰)  

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="DataToEncrypt">需加密的源字節</param>
        /// <param name="RSAKeyInfo">參數</param>
        /// <param name="DoOAEPPadding">使用OAEP填補</param>
        /// <returns></returns>
        static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                //Create a new instance of RSACryptoServiceProvider.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Import the RSA Key information. This only needs
                //toinclude the public key information.
                RSA.ImportParameters(RSAKeyInfo);

                //Encrypt the passed byte array and specify OAEP padding. 
                //OAEP padding is only available on Microsoft Windows XP or
                //later.
                return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
            }
            //Catch and display a CryptographicException 
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }

        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="DataToDecrypt">需解密的字節</param>
        /// <param name="RSAKeyInfo">參數</param>
        /// <param name="DoOAEPPadding">使用OAEP填補</param>
        /// <returns></returns>
        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                //Create a new instance of RSACryptoServiceProvider.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Import the RSA Key information. This needs
                //to include the private key information.
                RSA.ImportParameters(RSAKeyInfo);

                //Decrypt the passed byte array and specify OAEP padding. 
                //OAEP padding is only available on Microsoft Windows XP or
                //later. 
                return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
            }
            //Catch and display a CryptographicException 
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());

                return null;
            }

        }

        /// <summary>
        /// RSA加密,對數據簽名
        /// </summary>
        /// <param name="str_DataToSign">源字符串</param>
        /// <param name="str_Private_Key">私鑰</param>
        /// <returns>返回加密後的字串</returns>
        public static string RSAEncrypt(string str_DataToSign, string str_Public_Key)
        {
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(str_DataToSign);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.ImportCspBlob(Convert.FromBase64String(str_Public_Key));

            byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
            string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
            return str_Cypher_Text;
           
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="str_Cypher_Text">加過密的字串</param>
        /// <param name="str_Private_Key">私鑰</param>
        /// <returns>返回解密後的字串</returns>
        static public string RSADecrypt(string str_Cypher_Text, string str_Private_Key)
        {
            byte[] DataToDecrypt = Convert.FromBase64String(str_Cypher_Text);

            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            //RSA.ImportParameters(RSAKeyInfo);
            byte[] bytes_Public_Key = Convert.FromBase64String(str_Private_Key);
            RSA.ImportCspBlob(bytes_Public_Key);

            //OAEP padding is only available on Microsoft Windows XP or later. 
            byte[] bytes_Plain_Text = RSA.Decrypt(DataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            string str_Plain_Text = ByteConverter.GetString(bytes_Plain_Text);
            return str_Plain_Text;

        }

        /// <summary>
        /// 數字簽名
        /// </summary>
        /// <param name="str_DataToSign">需簽名的數據</param>
        /// <param name="str_Private_Key">自已的私鑰</param>
        /// <returns>返回簽名後的數據</returns>
        static public string RSASign(string str_DataToSign, string str_Private_Key)
        {
            ASCIIEncoding ByteConverter = new ASCIIEncoding();
            byte[] DataToSign = ByteConverter.GetBytes(str_DataToSign);
            try
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.ImportCspBlob(Convert.FromBase64String(str_Private_Key));
                byte[] signedData = RSA.SignData(DataToSign, new SHA1CryptoServiceProvider());
                string str_SignedData = Convert.ToBase64String(signedData);
                return str_SignedData;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        /// <summary>
        /// 利用對方公鑰驗證簽名
        /// </summary>
        /// <param name="str_DataToVerify">加密前的數據</param>
        /// <param name="str_SignedData">加密後的數據</param>
        /// <param name="str_Public_Key">公鑰</param>
        /// <returns></returns>
        public static bool RSAVerify(string str_DataToVerify, string str_SignedData, string str_Public_Key)
        {
            byte[] SignedData = Convert.FromBase64String(str_SignedData);

            ASCIIEncoding ByteConverter = new ASCIIEncoding();
            byte[] DataToVerify = ByteConverter.GetBytes(str_DataToVerify);

            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.ImportCspBlob(Convert.FromBase64String(str_Public_Key));

            return RSA.VerifyData(DataToVerify, new SHA1CryptoServiceProvider(), SignedData);

        }

        #endregion

    }

調用:
(1)MD5加密
 private void btnmd51_Click(object sender, EventArgs e)
        {
            this.txtmd52.Text = FileSecurity.Md5Encrypt16(this.txtmd51.Text);
        }

        private void btnmd52_Click(object sender, EventArgs e)
        {
            this.txtmd52.Text = FileSecurity.Md5Encrypt32(this.txtmd51.Text);
        }
(2)DES加解密
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string key = this.textBox1.Text;
                string IV = "12345678";
                byte[] deskey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
                byte[] desIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
                if (FileSecurity.DESEncrypt(this.textBox2.Text, this.textBox3.Text, deskey, desIV))
                {
                    MessageBox.Show("文件DES加密成功");
                }

                //string keys = this.txtDES1.Text;
                //this.txtDES3.Text=FileSecurity.DESEncrypt(this.txtDES2.Text, keys);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string key = this.txtDES1.Text;
                string IV = "12345678";
                byte[] deskey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
                byte[] desIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
                if (FileSecurity.DESDecrypt(this.txtDES2.Text, this.txtDES3.Text, deskey, desIV))
                {
                    MessageBox.Show("文件DES解密成功");
                }

                //string keys = this.txtDES1.Text;
                //this.txtDES3.Text = FileSecurity.DESDecrypt(this.txtDES2.Text, keys);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

(3)RC2加密
  private void btnRC21_Click(object sender, EventArgs e)
        {
            Byte[] keys = System.Text.Encoding.Unicode.GetBytes("天天向上");
            Byte[] iv = new Byte[]{0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

            this.txtRC22.Text = FileSecurity.RC2Decrypt(FileSecurity.RC2Encrypt(this.txtRC21.Text,keys,iv),keys,iv);
        }
(4)RSA加解密,簽名,驗證簽名
        private string str_Private_Key;
        private string str_Public_Key;
        private void btnRSA1_Click(object sender, EventArgs e)
        {
            try
            {
                string str_DataToSign = this.txtRSA1.Text;


                RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

                str_Private_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(true));
                str_Public_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(false));


                string str_SignedData = FileSecurity.RSAEncrypt(str_DataToSign, str_Public_Key);//Hash and sign the data.
                this.txtRSA2.Text = str_SignedData;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnRSA2_Click(object sender, EventArgs e)
        {
            try
            {
                string str_DataToSign = this.txtRSA1.Text;

                //RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

                //string str_Private_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(true));
                //string str_Public_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(false));


                string str_SignedData = FileSecurity.RSADecrypt(str_DataToSign, str_Private_Key);
                this.txtRSA2.Text = str_SignedData;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnRSA3_Click(object sender, EventArgs e)
        {
            string str_DataToSign = this.txtRSA1.Text;
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            string str_Private_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(true));
            string str_Public_Key = Convert.ToBase64String(RSAalg.ExportCspBlob(false));

            string str_SignedData = FileSecurity.RSASign(str_DataToSign, str_Private_Key);//加密

            this.txtRSA2.Text = str_SignedData;
            bool ok = false;
            ok = FileSecurity.RSAVerify(str_DataToSign, str_SignedData, str_Private_Key);//解密

            if (ok)
            {
                MessageBox.Show("ok");
            }
            else
            {
                MessageBox.Show("error");
            }

        }

3.生成隨機數
        /// <summary>
        /// 生成隨機數字
        /// </summary>
        /// <returns></returns>
        static int GetRandomInt()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        /// <summary>
        /// 生成隨機字符串
        /// </summary>
        /// <param name="length">長度</param>
        /// <param name="strSource">指定字符表</param>
        /// <returns></returns>
        static string GetRandomString(int length,string strSource)
        {
            //string strSource = "abcdefghijklmnopqrstuvwxyz";
            int strLen = strSource.Length;
            StringBuilder sbPwd = new StringBuilder();
            Random random = new Random(GetRandomInt());
            for (int i = 0; i < length; i++)
            {
                sbPwd.Append(strSource.Substring(random.Next(0, strLen), 1));
                //sbPwd.Append( sourceArray[random.Next( 0 , 25 )] );
            }
            return sbPwd.ToString();
        }
調用:
            this.txtRan1.Text = GetRandomSeed().ToString();
            this.txtRan2.Text = GetRandomString(10).ToString();


參考文獻:
http://blog.csdn.net/ehung/articles/842087.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值