CreateDecryptor() private method

private CreateDecryptor ( byte rgbKey, byte rgbIV ) : ICryptoTransform
rgbKey byte
rgbIV byte
return ICryptoTransform
        public string mDecryptURLEncode(string EncryptedText)
        {
            string DecryptedText = "";

            System.Security.Cryptography.ICryptoTransform ssd = rc2.CreateDecryptor();

            string sEncrypt = HttpUtility.UrlDecode(EncryptedText);

            byte[] cipherBytes = Convert.FromBase64String(sEncrypt);
            byte[] initialText = null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherBytes))
            {
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, ssd, System.Security.Cryptography.CryptoStreamMode.Read))
                {
                    int iCount = opGetArrLength(cipherBytes);
                    initialText = new Byte[cipherBytes.Length];
                    cs.Read(initialText, 0, initialText.Length);
                    cs.Close();
                    cs.Dispose();
                }
                ms.Close();
                ms.Dispose();
            }
            DecryptedText = System.Text.UTF8Encoding.UTF8.GetString(initialText);
            return(DecryptedText = DecryptedText.Replace("\0", ""));
        }
        /// <summary>
        /// Gets the crypto service provider.
        /// </summary>
        /// <param name="bytesKey">The bytes key.</param>
        /// <returns></returns>
		internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
		{
			switch(algorithmID)
			{
				case EncryptionAlgorithm.Des:
					DES des = new DESCryptoServiceProvider();
					des.Mode = CipherMode.CBC;
					des.Key = bytesKey;
					des.IV = initVec;
					return des.CreateDecryptor();

				case EncryptionAlgorithm.TripleDes:
					TripleDES des3 = new TripleDESCryptoServiceProvider();
					des3.Mode = CipherMode.CBC;
					return des3.CreateDecryptor(bytesKey, initVec);

				case EncryptionAlgorithm.Rc2:
					RC2 rc2 = new RC2CryptoServiceProvider();
					rc2.Mode = CipherMode.CBC;
					return rc2.CreateDecryptor(bytesKey, initVec);

				case EncryptionAlgorithm.Rijndael:
					Rijndael rijndael = new RijndaelManaged();
					rijndael.Mode = CipherMode.CBC;
					return rijndael.CreateDecryptor(bytesKey, initVec);

				default:
					throw new CryptographicException("Algorithm ID '" + algorithmID + "' not supported!");
			}
		}
        public static string DecryptPassword(string encryptedText)
        {
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.IV);
            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    List<Byte> bytes = new List<byte>();
                    int b;
                    do
                    {
                        b = csDecrypt.ReadByte();
                        if (b != -1)
                        {
                            bytes.Add(Convert.ToByte(b));
                        }

                    }
                    while (b != -1);

                    return Encoding.Unicode.GetString(bytes.ToArray());
                }
            }
        }
        public static string DecryptText(string encryptedText)
        {
            try
            {
                RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
                ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(C_KEY), Convert.FromBase64String(C_IV));
                MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText));
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                List<Byte> bytes = new List<byte>();
                int b;
                do
                {
                    b = csDecrypt.ReadByte();
                    if (b != -1)
                    {
                        bytes.Add(Convert.ToByte(b));
                    }

                } while (b != -1);

                return Encoding.Unicode.GetString(bytes.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }
Example #5
0
        public static string Decrypt(this string encrypted)
        {
            if (string.IsNullOrEmpty(encrypted)) { return string.Empty; }

            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV));
            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encrypted)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    List<Byte> bytes = new List<byte>();
                    int b;
                    do
                    {
                        b = csDecrypt.ReadByte();
                        if (b != -1)
                        {
                            bytes.Add(Convert.ToByte(b));
                        }

                    }
                    while (b != -1);

                    return Encoding.Unicode.GetString(bytes.ToArray());
                }
            }
        }
        /// <summary>
        /// Decrypt a Product Settings string.
        /// </summary>
        /// <param name="string">The string to decrypt.</param>
        /// <returns>The decrypted string.</returns>
        public static string Decrypt(string @string)
        {
            if (String.IsNullOrEmpty(@string))
                return @string;

            string result;
            try
            {
                byte[] bytes = Convert.FromBase64String(@string);
                using (MemoryStream dataStream = new MemoryStream(bytes))
                {
                    RC2CryptoServiceProvider cryptoService = new RC2CryptoServiceProvider
                    {
                        Key = Encoding.UTF8.GetBytes("ClearCanvas"),
                        IV = Encoding.UTF8.GetBytes("IsSoCool"),
                        UseSalt = false
                    };
                    using (CryptoStream cryptoStream = new CryptoStream(dataStream, cryptoService.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(cryptoStream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                            reader.Close();
                        }
                        cryptoStream.Close();
                    }
                    dataStream.Close();
                }
            }
            catch (Exception)
            {
                result = string.Empty;
            }
            return result;
        }
 public static string Decrypt(string input, string key)
 {
     byte[] inputArray = System.Convert.FromBase64String(input);
     RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
     rc2.Key = UTF8Encoding.UTF8.GetBytes(key);
     rc2.Mode = CipherMode.ECB;
     rc2.Padding = PaddingMode.PKCS7;
     ICryptoTransform cTransform = rc2.CreateDecryptor();
     byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
     rc2.Clear();
     return UTF8Encoding.UTF8.GetString(resultArray);
 }
Example #8
0
        /// <summary>
        /// 解密数据.
        /// </summary>
        /// <param name="toDecrypt">要解密的密文.</param>
        /// <returns></returns>
        private string RC2Decrypt(byte[] toDecrypt)
        {
            RC2CryptoServiceProvider myRC2 = new RC2CryptoServiceProvider();
            ICryptoTransform myCryptoTrans = myRC2.CreateDecryptor(Key, IV);
            MemoryStream ms = new MemoryStream(toDecrypt);
            CryptoStream cs = new CryptoStream(ms, myCryptoTrans, CryptoStreamMode.Read);
            byte[] tmp = new byte[toDecrypt.Length];

            cs.Read(tmp, 0, tmp.Length);
            ms.Close();
            cs.Close();
            return Encoding.UTF8.GetString(tmp);
        }
Example #9
0
        public void Decrypt()
        {
            using (SymmetricAlgorithm rc2Csp = new RC2CryptoServiceProvider())
            {
                rc2Csp.Key = getByts(this._CryptoKey);
                rc2Csp.IV = getByts(IV);

                using (ICryptoTransform encryptor = rc2Csp.CreateDecryptor())
                {
                    byte[] source = Convert.FromBase64String(_EncryptionMessage);
                    byte[] decrypted = encryptor.TransformFinalBlock(source, 0, source.Length);

                    this._NomalMessage=Encoding.UTF8.GetString(decrypted);
                }
            }
        }
Example #10
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public override string DoDecrypt(string encryptedText, string key, Encoding encoding, DataMode encryptedType)
 {
     MemoryStream stream = new MemoryStream(200);
     stream.SetLength(0L);
     byte[] buffer = Convert.FromBase64String(encryptedText);
     RC2 rc = new RC2CryptoServiceProvider();
     rc.KeySize = 0x40;
     CryptoStream stream2 = new CryptoStream(stream, rc.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
     stream2.Write(buffer, 0, buffer.Length);
     stream2.FlushFinalBlock();
     stream.Flush();
     stream.Seek(0L, SeekOrigin.Begin);
     byte[] buffer2 = new byte[stream.Length];
     stream.Read(buffer2, 0, buffer2.Length);
     stream2.Close();
     stream.Close();
     return Encoding.Unicode.GetString(buffer2);
 }
Example #11
0
File: RC.cs Project: VqSoft/ZYFC
 /// <summary> 
 /// 进行RC2解密。 
 /// </summary> 
 /// <param name="pToDecrypt">要解密的以Base64</param> 
 /// <param name="sKey">初始化向量</param> 
 /// <param name="IV">密钥,且必须为8位。</param> 
 /// <returns>已解密的字符串。</returns> 
 public static string Decrypt(string pToDecrypt, byte[] key, byte[] IV)
 {
     byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
     using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider())
     {
         System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateDecryptor(key, IV);
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         using (CryptoStream cs = new CryptoStream(ms, Encryptor, CryptoStreamMode.Write))
         {
             cs.Write(inputByteArray, 0, inputByteArray.Length);
             cs.FlushFinalBlock();
             cs.Close();
         }
         string str = Encoding.UTF8.GetString(ms.ToArray());
         ms.Close();
         return str;
     }
 }
Example #12
0
 //����
 //����:strData:Ҫ���ܵ����� strKey:��Կ
 //����:����ܵ��ַ���
 public static string Decrypt(string strData, string strKey)
 {
     try
     {
         RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();
         byte[] key = System.Text.Encoding.Unicode.GetBytes(strKey);
         byte[] data = System.Text.Encoding.Unicode.GetBytes(strData);
         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());
     }
     catch
     {
         return "";
     }
 }
Example #13
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider())
            {
                rc2.Padding = PaddingMode.None;

                rc2.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                rc2.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                //ICryptoTransform decryptor = aes.CreateDecryptor();
                using (ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key, rc2.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
                }
            }
        }
Example #14
0
        public static string RC2Decrypt(byte[] bytes, string encryptionKey, string vector)
        {
            byte[] key = CalculateMD5Hash(encryptionKey);
            byte[] IV = new byte[64];
            IV.Initialize();
            byte[] varr = Encoding.ASCII.GetBytes(vector);
            Buffer.BlockCopy(varr, 0, IV, 0, varr.Length > 64 ? 64 : varr.Length);

            RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
            ICryptoTransform dec = rc2.CreateDecryptor(key, IV);
            MemoryStream stream = new MemoryStream(bytes);
            CryptoStream cs = new CryptoStream(stream, dec, CryptoStreamMode.Read);
            byte[] block = new byte[8000];
            MemoryStream ms = new MemoryStream();
            int n;
            do
            {
                n = cs.Read(block, 0, block.Length);
                ms.Write(block, 0, n);
            } while (n == block.Length);
            return Encoding.ASCII.GetString(ms.ToArray());
        }
        public ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            ICryptoTransform iCryptoTransform;

            switch (this.algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    DES dES = new DESCryptoServiceProvider();
                    dES.Mode = CipherMode.CBC;
                    dES.Key = bytesKey;
                    dES.IV = this.initVec;
                    iCryptoTransform = dES.CreateDecryptor();
                    break;

                case EncryptionAlgorithm.TripleDes:
                    TripleDES tripleDES = new TripleDESCryptoServiceProvider();
                    tripleDES.Mode = CipherMode.CBC;
                    iCryptoTransform = tripleDES.CreateDecryptor(bytesKey, this.initVec);
                    break;

                case EncryptionAlgorithm.Rc2:
                    RC2 rC2 = new RC2CryptoServiceProvider();
                    rC2.Mode = CipherMode.CBC;
                    iCryptoTransform = rC2.CreateDecryptor(bytesKey, this.initVec);
                    break;

                case EncryptionAlgorithm.Rijndael:
                    Rijndael rijndael = new RijndaelManaged();
                    rijndael.Mode = CipherMode.CBC;
                    iCryptoTransform = rijndael.CreateDecryptor(bytesKey, this.initVec);
                    break;

                default:
                    throw new CryptographicException(String.Concat("Algorithm ID \'", this.algorithmID,
                                                                   "\' not supported."));
            }
            return iCryptoTransform;
        }
		internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
		{
			// Pick the provider.
			switch (_algorithmID)
			{
				case EncryptionAlgorithm.Des:
				{
					DES des = new DESCryptoServiceProvider();
					des.Mode = CipherMode.CBC;
					des.Key = bytesKey;
					des.IV = _initVec;
					return des.CreateDecryptor();
				}
				case EncryptionAlgorithm.TripleDes:
				{
					TripleDES des3 = new TripleDESCryptoServiceProvider();
					des3.Mode = CipherMode.CBC;
					return des3.CreateDecryptor(bytesKey, _initVec);
				}
				case EncryptionAlgorithm.Rc2:
				{
					RC2 rc2 = new RC2CryptoServiceProvider();
					rc2.Mode = CipherMode.CBC;
					return rc2.CreateDecryptor(bytesKey, _initVec);
				}
				case EncryptionAlgorithm.Rijndael:
				{
					Rijndael rijndael = new RijndaelManaged();
					rijndael.Mode = CipherMode.CBC;
					return rijndael.CreateDecryptor(bytesKey, _initVec);
				}
				default:
				{
					throw new CryptographicException("Algorithm ID '" + _algorithmID +
						"' not supported.");
				}
			}
		} //end GetCryptoServiceProvider
Example #17
0
        /// <summary>
        /// Do Decrypt from encryptedBase64String.
        /// </summary>
        /// <param name="encryptedBase64String">Base64 string of encrypted.</param>
        /// <returns>Plain string.</returns>
        public string Decrypt(string encryptedBase64String)
        {
            // Create the file streams to handle the input and output files.
            MemoryStream fout = new MemoryStream(200);
            fout.SetLength(0);

            // Create variables to help with read and write.
            byte[] bin = Convert.FromBase64String(encryptedBase64String);
            RC2 rc = new RC2CryptoServiceProvider();
            rc.KeySize = 64;
            CryptoStream encStream = new CryptoStream(fout, rc.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
            encStream.Write(bin, 0, bin.Length);
            encStream.FlushFinalBlock();
            fout.Flush();
            fout.Seek(0, SeekOrigin.Begin);

            // read all string
            byte[] bout = new byte[fout.Length];
            fout.Read(bout, 0, bout.Length);
            encStream.Close();
            fout.Close();
            return System.Text.Encoding.Unicode.GetString(bout);
        }
Example #18
0
 internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
 {
     // 获取解密服务端の提供者
     switch (algorithmID)
     {
         case EncryptionAlgorithm.Des:
             {
                 DES des = new DESCryptoServiceProvider();
                 des.Mode = CipherMode.CBC;
                 des.Key = bytesKey;
                 des.IV = IV;
                 return des.CreateDecryptor();
             }
         case EncryptionAlgorithm.TripleDes:
             {
                 TripleDES tripleDes = new TripleDESCryptoServiceProvider();
                 tripleDes.Mode = CipherMode.CBC;
                 return tripleDes.CreateDecryptor(bytesKey, IV);
             }
         case EncryptionAlgorithm.Rc2:
             {
                 RC2 rc2 = new RC2CryptoServiceProvider();
                 rc2.Mode = CipherMode.CBC;
                 return rc2.CreateDecryptor(bytesKey, IV);
             }
         case EncryptionAlgorithm.Rijndael:
             {
                 Rijndael rijndael = new RijndaelManaged();
                 rijndael.Mode = CipherMode.CBC;
                 return rijndael.CreateDecryptor(bytesKey, IV);
             }
         default:
             {
                 throw new CryptographicException("不支持の" + "解密算法ID: '" + algorithmID + "' ");
             }
     }
 }
 /// <summary>
 /// �����ṩ��ö����Ϣ,�����Ҫʹ�õĽ����㷨�Ľӿ�
 /// </summary>
 /// <param name="algorithm"></param>
 /// <returns></returns>
 internal ICryptoTransform GetDecryptoServiceProvider(EncryptionAlgorithm algorithm)
 {
     switch (algorithm)
     {
         case EncryptionAlgorithm.Des:
             {
                 DES des = new DESCryptoServiceProvider();
                 des.Mode = CipherMode.CBC;
                 if (this.m_Key != null)
                 {
                     des.Key = m_Key;
                 }
                 if (m_initVec != null)
                 {
                     des.IV = m_initVec;
                 }
                 return des.CreateDecryptor();
             }
         case EncryptionAlgorithm.Rc2:
             {
                 RC2 rc = new RC2CryptoServiceProvider();
                 rc.Mode = CipherMode.CBC;
                 return rc.CreateDecryptor(m_Key, m_initVec);
             }
         case EncryptionAlgorithm.Rijndael:
             {
                 Rijndael rijndael = new RijndaelManaged();
                 rijndael.Mode = CipherMode.CBC;
                 return rijndael.CreateDecryptor(m_Key, m_initVec);
             }
         case EncryptionAlgorithm.TripleDes:
             {
                 TripleDES edes = new TripleDESCryptoServiceProvider();
                 edes.Mode = CipherMode.CBC;
                 return edes.CreateDecryptor(m_Key, m_initVec);
             }
     }
     throw new CryptographicException("Algorithm ID '" + algorithm + "' not supported.");
 }
Example #20
0
        static void Main(string[] args)
        {
            const int n = 100 * 1000;
            var sw = new Stopwatch();
            Random r = new Random();
            var data = new byte[1024];
            var key8B = new byte[8];
            var key16B = new byte[16];
            var key24B = new byte[24];
            var key32B = new byte[32];
            r.NextBytes(data);
            r.NextBytes(key8B);
            r.NextBytes(key16B);
            r.NextBytes(key24B);
            r.NextBytes(key32B);
            Action<string> outputToConsole = (s) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(s);
            };

            // AES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("AES");
            var aes = new AesCryptoServiceProvider();
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = key16B;
            Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data);
            doAes.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            aes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("DES");
            var des = new DESCryptoServiceProvider();
            des.IV = key8B;
            des.Key = key8B;
            Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data);
            doDes.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            des.Dispose();

            // RC2
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RC2");
            var rc2 = new RC2CryptoServiceProvider();
            rc2.IV = key8B;
            rc2.Key = key8B;
            Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data);
            doRc2.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rc2.Dispose();

            // Rijndael
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Rijndael");
            var rijndael = new RijndaelManaged();
            rijndael.IV = key16B;
            rijndael.Key = key16B;
            Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data);
            doRijndael.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rijndael.Dispose();

            // 3DES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("3DES");
            var tripleDes = new TripleDESCryptoServiceProvider();
            tripleDes.IV = key8B;
            tripleDes.Key = key24B;
            Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data);
            do3des.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            tripleDes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RSA");
            RSAParameters param = new RSAParameters();
            param.Exponent = new byte[] {0, 1, 0};
            var store = new X509Store(StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate cert = null;
            foreach (X509Certificate cer in store.Certificates)
            {
                if (cer != null)
                {
                    cert = cer;
                    break;
                }
            }
            param.Modulus = cert.GetPublicKey();

            var rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(param);

            Action doRsa = () =>
                {

                    var encryptedData = rsa.Encrypt(key32B, true);
                    //var decryptedData = rsa.Decrypt(encryptedData, true);
                };
            doRsa.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rsa.Dispose();

            Console.Read();
        }
Example #21
0
 public static string RC2Decrypt(string decryptString, string decryptKey, string t)
 {
     string returnValue;
     try
     {
         byte[] temp = UTF8Encoding.UTF8.GetBytes(t);
         //byte[] temp = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xFF };
         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
     {
         returnValue = null;
     }
     return returnValue;
 }
Example #22
0
        //解密
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                //图片流
                FileStream fsPic = new FileStream(pictureBox1.ImageLocation, FileMode.Open, FileAccess.Read);
                //解密文件流
                FileStream fsOut = File.Open(textBox1.Text, FileMode.Open, FileAccess.Read);
                //初始化Key IV
                byte[] bykey = new byte[16];
                byte[] byIv = new byte[8];
                fsPic.Read(bykey, 0, 16);
                fsPic.Read(byIv, 0, 8);
                //临时解密文件
                string strPath = textBox1.Text;//加密文件的路径
                int intLent = strPath.LastIndexOf("\\") + 1;
                int intLong = strPath.Length;
                string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
                string strLinPath = "C:\\" + strName;//临时解密文件路径
                FileStream fs = new FileStream(strLinPath, FileMode.Create, FileAccess.Write);
                //开始解密
                RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des进行解
                CryptoStream csDecrypt = new CryptoStream(fsOut, desc.CreateDecryptor(bykey, byIv), CryptoStreamMode.Read);//读出加密文件
                BinaryReader sr = new BinaryReader(csDecrypt);//从要加密流中读出文件内容
                BinaryWriter sw = new BinaryWriter(fs);//写入解密流
                sw.Write(sr.ReadBytes(Convert.ToInt32(fsOut.Length)));//
                sw.Flush();
                sw.Close();
                sr.Close();
                fs.Close();
                fsOut.Close();
                fsPic.Close();
                csDecrypt.Flush();

                File.Delete(textBox1.Text.TrimEnd());//册除原文件
                File.Copy(strLinPath, textBox1.Text);//复制加密文件
                File.Delete(strLinPath);//册除临时文件
                MessageBox.Show("解密成功");
                pictureBox1.ImageLocation = null;
                textBox1.Text = "";
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
Example #23
0
 /// <summary>
 ///  RC2解密
 /// </summary>
 /// <param name="value">密文</param>
 /// <param name="key">密钥</param>
 /// Author  : 俞立钢
 /// Company : 绍兴标点电子技术有限公司
 /// Created : 2014-12-11 14:31:15
 public static string DecrypteRc2(this string value, string key)
 {
     try
     {
         RC2CryptoServiceProvider mRc2Provider = new RC2CryptoServiceProvider();
         ICryptoTransform cryptoTransform = mRc2Provider.CreateDecryptor(Encoding.Default.GetBytes(key),
             PublicFields.MbtIv);
         return DecrypteMethod(value, cryptoTransform);
     }
     catch (Exception)
     {
         return "RC2解密失败!";
     }
 }
Example #24
0
        public ICryptoTransform GetCryptoTransform()
        {
            bool bHasSecuityKey = false;
            if (SecurityKey.Length != 0)
                bHasSecuityKey = true;

            byte[] key = Encoding.ASCII.GetBytes(SecurityKey);
            switch (algorithmID)
            {
                case EncryptionAlgorithm.DES:
                    DES des = new DESCryptoServiceProvider();
                    if (bHasSecuityKey) des.Key = key;
                    if (bHasIV) des.IV = IV;
                    return des.CreateDecryptor();

                case EncryptionAlgorithm.Rc2:
                    RC2 rc = new RC2CryptoServiceProvider();
                    if (bHasSecuityKey) rc.Key = key;
                    if (bHasIV) rc.IV = IV;
                    return rc.CreateDecryptor();
                case EncryptionAlgorithm.Rijndael:
                    Rijndael rj = new RijndaelManaged();
                    if (bHasSecuityKey) rj.Key = key;
                    if (bHasIV) rj.IV = IV; ;
                    return rj.CreateDecryptor();
                case EncryptionAlgorithm.TripleDes:
                    TripleDES tDes = new TripleDESCryptoServiceProvider();
                    if (bHasSecuityKey) tDes.Key = key;
                    if (bHasIV) tDes.IV = IV;
                    return tDes.CreateDecryptor();
                default:
                    throw new CryptographicException("Algorithm ID '" + algorithmID + "' not supported.");
            }
        }
Example #25
0
        public static void MainX()
        {
            IPTSession session = SessionManager.CreateSession("Administrator", "");

            IPTSession guestSession = session.ImpersonateUser("Guest");

            IPTSessionInfo info = guestSession.GetSessionInfo();

            object [][] val = info.LookupPreference("myTestPref", 0);

            Console.WriteLine("Preference value is: " + val[1][0].ToString());

            IApplication application = ApplicationManager.GetInstance().GetApplication(AppConstants.MAIN_APPLICATION_NAME.ToString());

            application.GetCachingManager().SetEntry("", val[1][0].ToString());

            return;

            IXPCrypto xpcpPass = XPCrypto.GetInstance(XPCryptoType.RC2_40);
            string pwd = xpcpPass.Encrypt("password", "pthack");

            // Create a new instance of the RC2CryptoServiceProvider class
            // and automatically generate a Key and IV.
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

            Console.WriteLine("Effective key size is {0} bits.", rc2CSP.EffectiveKeySize);

            string strToDecrypt = "P4uUnYhwaRmldZEyAee3QWuoA==";//"6200E0C962077DDBACEBCC3BEA5C3BEA260B45CCC695A003";
            string strKey = "blahuser"; //"Administrator";

            // Get the key and IV.

            if (strToDecrypt.StartsWith("P")) {
                strKey = strToDecrypt.Substring(1, 2) + strKey;
            } else {

            }
            string sKey = strToDecrypt.Substring(1, 2) + strKey;

            byte[] key =  GetCryptKey(sKey);//rc2CSP.Key;
            byte[] IV = iv; // rc2CSP.IV;

            string encryptedText = strToDecrypt.Substring(3);
            byte[] encrypted = System.Convert.FromBase64String(encryptedText);

            //Get a decryptor that uses the same key and IV as the encryptor.
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV);

            // Now decrypt the previously encrypted message using the decryptor
            // obtained in the above step.
            MemoryStream msDecrypt = new MemoryStream(encrypted);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

            // Read the decrypted bytes from the decrypting stream
            // and place them in a StringBuilder class.

            StringBuilder roundtrip = new StringBuilder();

            int b = 0;

            do {
                b = csDecrypt.ReadByte();

                if (b != -1) {
                    roundtrip.Append((char)b);
                }

            } while (b != -1);

            // Display the original data and the decrypted data.
            //Console.WriteLine("Original:   {0}", original);
            Console.WriteLine("Round Trip: {0}", roundtrip);

            Console.ReadLine();
        }
Example #26
0
 internal ICryptoTransform getServiceProvider(cryptoAction cAction, byte[] key, byte[] IV)
 {
     ICryptoTransform transform = null;
     switch (algorithm)
     {
         case cryptoProvider.DES:
             var des = new DESCryptoServiceProvider();
             switch (cAction)
             {
                 case cryptoAction.Encrypt:
                     // si estamos cifrando, creamos el objeto cifrador.
                     transform = des.CreateEncryptor(key, IV);
                     break;
                 case cryptoAction.Decrypt:
                     // si estamos descifrando, creamos el objeto descifrador.
                     transform = des.CreateDecryptor(key, IV);
                     break;
             }
             return transform;
         case cryptoProvider.TripleDES:
             var des3 = new TripleDESCryptoServiceProvider();
             switch (cAction)
             {
                 case cryptoAction.Encrypt:
                     transform = des3.CreateEncryptor(key, IV);
                     break;
                 case cryptoAction.Decrypt:
                     transform = des3.CreateDecryptor(key, IV);
                     break;
             }
             return transform;
         case cryptoProvider.RC2:
             var rc2 = new RC2CryptoServiceProvider();
             switch (cAction)
             {
                 case cryptoAction.Encrypt:
                     transform = rc2.CreateEncryptor(key, IV);
                     break;
                 case cryptoAction.Decrypt:
                     transform = rc2.CreateDecryptor(key, IV);
                     break;
             }
             return transform;
         case cryptoProvider.Rijndael:
             var rijndael = new RijndaelManaged();
             switch (cAction)
             {
                 case cryptoAction.Encrypt:
                     transform = rijndael.CreateEncryptor(key, IV);
                     break;
                 case cryptoAction.Decrypt:
                     transform = rijndael.CreateDecryptor(key, IV);
                     break;
             }
             return transform;
         default:
             throw new CryptographicException("Error al inicializar al proveedor de cifrado");
     }
 }
            /// <summary>
            /// Decrypt incoming message
            /// </summary>
            public bool Decrypt(NetIncomingMessage msg)
            {
                try
                {
                    // nested usings are fun!
                    using (RC2CryptoServiceProvider rc2CryptoServiceProvider = new RC2CryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC })
                    {
                        using (ICryptoTransform cryptoTransform = rc2CryptoServiceProvider.CreateDecryptor(m_key, m_iv))
                        {
                            using (MemoryStream memoryStream = new MemoryStream())
                            {
                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                                                                 CryptoStreamMode.Write))
                                {
                                    cryptoStream.Write(msg.m_data, 0, msg.m_data.Length);
                                }
                                msg.m_data = memoryStream.ToArray();
                            }
                        }
                    }

                }
                catch
                {
                    return false;
                }
                return true;
            }
Example #28
0
 public static string Decrypt(string pvDataString)
 {
     try
     {
         RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider();
         byte[] fvKey = RC2.Key;
         byte[] IV = RC2.IV;
         ICryptoTransform fvDecryptor = RC2.CreateDecryptor(fvKey, IV);
         MemoryStream fvMsDecrypt = new MemoryStream(Convert.FromBase64String(pvDataString));
         CryptoStream csDecrypt = new CryptoStream(fvMsDecrypt, fvDecryptor, CryptoStreamMode.Read);
         StreamReader fvSr = new StreamReader(csDecrypt);
         string fvVal = fvSr.ReadLine();
         fvSr.Close();
         csDecrypt.Close();
         fvMsDecrypt.Close();
         return fvVal;
     }
     catch
     {
         return "BADDATA";
     }
 }
        private static string RC2Decrypt(string algorithm, string CipherText, string PassWord)
        {
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
            byte[] ciphertextBytes = Convert.FromBase64String(CipherText);

            PasswordDeriveBytes passwordBytes = new PasswordDeriveBytes(PassWord, saltValueBytes, algorithm, passwordIterations);
            byte[] keyBytes = passwordBytes.GetBytes(keySize / 8);

            RC2CryptoServiceProvider symmetricKey = new RC2CryptoServiceProvider();
            symmetricKey.Mode = CipherMode.CBC;

            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            MemoryStream memStream = new MemoryStream(ciphertextBytes);
            CryptoStream cryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);

            byte[] plainTextBytes = new byte[ciphertextBytes.Length];
            int decryptedByteCount = cryptStream.Read(plainTextBytes, 0, plainTextBytes.Length);

            memStream.Close();
            cryptStream.Close();

            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        }
Example #30
0
        /// <summary>
        /// RC2 解密(用变长密钥对大量数据进行加密)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        /// <returns>returns</returns>
        public static string RC2Decrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }

            if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }

            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            string m_strDecrypt = "";

            RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_cstream.Close(); m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_RC2Provider.Clear(); }
            return m_strDecrypt;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bytesKey"></param>
 /// <returns></returns>
 public ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
 {
     //当数据密钥Key或者初始化向量IV为空的时候,将使用加密对象自动产生的密钥Key或者初始化向量IV 
     switch (algorithmID)
     {
         case EncryptionAlgorithm.Des:
             {
                 System.Security.Cryptography.DES des = new DESCryptoServiceProvider();
                 des.Mode = CipherMode.CBC;
                 des.Key = bytesKey;
                 des.IV = initVec;
                 return des.CreateDecryptor();
             }
         case EncryptionAlgorithm.TripleDes:
             {
                 TripleDES des3 = new TripleDESCryptoServiceProvider();
                 des3.Mode = CipherMode.CBC;
                 return des3.CreateDecryptor(bytesKey, initVec);
             }
         case EncryptionAlgorithm.Rc2:
             {
                 RC2 rc2 = new RC2CryptoServiceProvider();
                 rc2.Mode = CipherMode.CBC;
                 return rc2.CreateDecryptor(bytesKey, initVec);
             }
         case EncryptionAlgorithm.Rijndael:
             {
                 Rijndael rijndael = new RijndaelManaged();
                 rijndael.Mode = CipherMode.CBC;
                 return rijndael.CreateDecryptor(bytesKey, initVec);
             }
         default:
             {
                 throw new CryptographicException("Algorithm ID ''" +
                 algorithmID +
                 "'' not supported.");
             }
     }
 }