C#對稱加密(3des)和非對稱加密(rsa)算法

3DES加密/解密算法的C#實現:(實現的方式不少,僅供參考)算法

public static bool DecryptFromBase64(string base64String, string key,out string DecryptString)
        {
            DecryptString = "";
            try
            {
                // encode to bytes
                byte[] KEY = HexStringToByteArray(key);
                byte[] CRYPTSTRING = Convert.FromBase64String(base64String);

                //set iv and key
                byte[] tmpiv = { 49, 50, 51, 52, 53, 54, 55, 56 };
                byte[] tmpkey = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 };


                for (int ii = 0; ii < 24; ii++)
                {
                    tmpkey[ii] = KEY[ii];
                }

                TripleDESCryptoServiceProvider dsp = new TripleDESCryptoServiceProvider();
                dsp.Mode = System.Security.Cryptography.CipherMode.CBC;
                dsp.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                ICryptoTransform tridesencrypt = dsp.CreateDecryptor(tmpkey, tmpiv);

                using (var ms = new MemoryStream(CRYPTSTRING))
                {
                    using (var cs = new CryptoStream(ms, tridesencrypt, CryptoStreamMode.Read))
                    {
                        var sr = new StreamReader(cs, Encoding.UTF8);
                        // 2015/11/11 修改 讀取所有內容,而不是隻讀第一行,此問題乃是算法的bug
                        DecryptString = sr.ReadToEnd();// sr.ReadLine();
                    }
                }

                dsp.Clear();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public static bool Crypt3DESToBase64(string CryptString, string Key, out string DecryptString)
        {
            DecryptString = "";
            try
            {
                // encode to bytes
                byte[] KEY = HexStringToByteArray(Key);
                byte[] CRYPTSTRING = System.Text.Encoding.UTF8.GetBytes(CryptString);

                //set iv and key
                byte[] tmpiv = { 49, 50, 51, 52, 53, 54, 55, 56 };
                byte[] tmpkey = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 };


                for (int ii = 0; ii < 24; ii++)
                {
                    tmpkey[ii] = KEY[ii];
                }

                TripleDESCryptoServiceProvider dsp = new TripleDESCryptoServiceProvider();
                dsp.Mode = System.Security.Cryptography.CipherMode.CBC;
                dsp.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                ICryptoTransform tridesencrypt = dsp.CreateEncryptor(tmpkey, tmpiv);

                byte[] results = tridesencrypt.TransformFinalBlock(CRYPTSTRING, 0, CRYPTSTRING.Length);

                DecryptString = Convert.ToBase64String(results);

                dsp.Clear();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public static byte[] HexStringToByteArray(string s)
        {
            Byte[] buf = new byte[s.Length / 2];
            for (int i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)(chr2hex(s.Substring(i * 2, 1)) * 0x10 + chr2hex(s.Substring(i * 2 + 1, 1)));
            }
            return buf;
        }

        private static byte chr2hex(string chr)
        {
            switch (chr)
            {
                case "0":
                    return 0x00;
                case "1":
                    return 0x01;
                case "2":
                    return 0x02;
                case "3":
                    return 0x03;
                case "4":
                    return 0x04;
                case "5":
                    return 0x05;
                case "6":
                    return 0x06;
                case "7":
                    return 0x07;
                case "8":
                    return 0x08;
                case "9":
                    return 0x09;
                case "A":
                    return 0x0a;
                case "B":
                    return 0x0b;
                case "C":
                    return 0x0c;
                case "D":
                    return 0x0d;
                case "E":
                    return 0x0e;
                case "F":
                    return 0x0f;
            }
            return 0x00;
        }

  在以上算法中,key爲一個48位的字符串,別的就沒特別要注意的了。數組

RSA加密算法(根據MSDN文檔實現):ide

        /// <summary>
        /// 使用rsa非對稱加密算法加密文本內容
        /// </summary>
        /// <param name="contentBytes">待加密內容byte數組</param>
        /// <param name="publicKey">公開密鑰</param>
        /// <param name="DoOAEPPadding">建議爲false</param>
        /// <returns>加密後的byte[]</returns>
        public static byte[] RSAEncryptContent(byte[]contentBytes,RSAParameters publicKey,bool DoOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider())
                {
                    provider.ImportParameters(publicKey);

                    encryptedData = provider.Encrypt(contentBytes, DoOAEPPadding);
                }
                return encryptedData;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// 使用rsa非對稱加密算法進行解密
        /// </summary>
        /// <param name="cryptContentBytes">加密後的字節數組</param>
        /// <param name="privateKey">私有密鑰</param>
        /// <param name="DoOAEPPadding">建議爲false</param>
        /// <returns>解密後的內容數組</returns>
        public static byte[] RSADescryptContent(byte[]cryptContentBytes,RSAParameters privateKey,bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptData;
                using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider())
                {
                    provider.ImportParameters(privateKey);

                    decryptData = provider.Decrypt(cryptContentBytes, DoOAEPPadding);
                }
                return decryptData;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }

  使用RSA加密/解密算法的方法:加密

                   //content爲要進行加密的字符串            byte[] contentBytes = byteConverter.GetBytes(content);
            byte[] encryptBytes;
            byte[] decryptBytes;

            //待加密的字節數不能超過密鑰的長度值除以 8 再減去 11(即:RSACryptoServiceProvider.KeySize / 8 - 11)
            int maxBlockSize;
            using(RSACryptoServiceProvider provider=new RSACryptoServiceProvider())
            {
                maxBlockSize = provider.KeySize / 8 - 11;

                RSAParameters publicKey = provider.ExportParameters(false);

                // 小於最大塊值,直接加密
                if (contentBytes.Length <= maxBlockSize)
                {
                    encryptBytes = EncryptContent(contentBytes, publicKey, false);
                }
                else
                {
                    // 分塊兒加密
                    using(MemoryStream plaintStream=new MemoryStream(contentBytes))
                    using(MemoryStream cryptStream=new MemoryStream())
                    {
                        byte[] buffer = new byte[maxBlockSize];
                        int blockSize = plaintStream.Read(buffer, 0, maxBlockSize);
                        while(blockSize>0)
                        {
                            byte[] encryptBlock = new byte[blockSize];
                            Array.Copy(buffer, encryptBlock, blockSize);
                            byte[]encryptedBlock=EncryptContent(encryptBlock,publicKey,false);
                            cryptStream.Write(encryptedBlock, 0, encryptedBlock.Length);

                            blockSize = plaintStream.Read(buffer, 0, maxBlockSize);
                        }
                        encryptBytes = cryptStream.ToArray();
                    }
                }
                //加密後的字符串
                string encryptString = byteConverter.GetString(encryptBytes);

                Console.WriteLine("加密結束");
                Console.ReadLine();
                Console.ReadLine();                // 如下爲解密過程,解密過程也會有長度限制,可參考加密的方式進行解密
                //string encryptString = byteConverter.GetString(encryptBytes);

                //RSAParameters privateKey = provider.ExportParameters(true);

                //decryptBytes = DecryptContent(encryptBytes, privateKey, false);

                //string decryptString = byteConverter.GetString(decryptBytes);
                //Console.WriteLine(decryptString);
            }
相關文章
相關標籤/搜索