private void rc2Encryption(String cipher, String padding, String key)
        {
            using (RC2 rc2 = RC2.Create())
            {
                rc2.Mode    = (CipherMode)Enum.Parse(typeof(CipherMode), cipher, true);
                rc2.Padding = (PaddingMode)Enum.Parse(typeof(PaddingMode), padding, true);
                rc2.KeySize = 128;
                rc2.Key     = getBytes(this.KeyTextBox.Text);

                string input = File.ReadAllText(this.InputTextBox.Text);

                ICryptoTransform encryptor = rc2.CreateEncryptor(rc2.Key, rc2.IV);
                byte[]           encrypted;
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(input);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }

                File.WriteAllBytes(this.OutputTextBox.Text, encrypted);
                MessageBox.Show("Succesfuly encrypted!");
            }
        }
Example #2
0
        private void CheckECB(int effective_bits, byte[] key, byte[] pt, byte[] expected)
        {
            RC2 c = RC2.Create();

            c.Mode    = CipherMode.ECB;
            c.Padding = PaddingMode.Zeros;
            c.Key     = key;
            Assert.AreEqual(key.Length * 8, c.KeySize, "KeySize");
            c.EffectiveKeySize = effective_bits;

            ICryptoTransform encryptor = c.CreateEncryptor();
            ICryptoTransform decryptor = c.CreateDecryptor();

            byte[] ct = new byte [pt.Length];
            int    n  = encryptor.TransformBlock(pt, 0, pt.Length, ct, 0);

            Assert.AreEqual(n, pt.Length, "EncryptLen");
            for (int i = 0; i < n; i++)
            {
                Assert.AreEqual(ct[i], expected[i], "Encrypt" + i);
            }

            byte[] rt = new byte [ct.Length];
            n = decryptor.TransformBlock(ct, 0, ct.Length, rt, 0);
            Assert.AreEqual(n, ct.Length, "DecryptLen");
            for (int i = 0; i < n; i++)
            {
                Assert.AreEqual(rt[i], pt[i], "Decrypt" + i);
            }
        }
        public static void InvalidCFBFeedbackSizes(int feedbackSize, bool discoverableInSetter)
        {
            using (RC2 rc2 = RC2Factory.Create())
            {
                rc2.GenerateKey();
                rc2.Mode = CipherMode.CFB;

                if (discoverableInSetter)
                {
                    // there are some key sizes that are invalid for any of the modes,
                    // so the exception is thrown in the setter
                    Assert.Throws <CryptographicException>(() =>
                    {
                        rc2.FeedbackSize = feedbackSize;
                    });
                }
                else
                {
                    rc2.FeedbackSize = feedbackSize;

                    // however, for CFB only few sizes are valid. Those should throw in the
                    // actual RC2 instantiation.

                    Assert.Throws <CryptographicException>(() => rc2.CreateDecryptor());
                    Assert.Throws <CryptographicException>(() => rc2.CreateEncryptor());
                }
            }
        }
Example #4
0
        private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            // Create a MemoryStream to accept the encrypted bytes
            MemoryStream ms = new MemoryStream();



            RC2 alg = RC2.Create();

            alg.Key = Key;
            alg.IV  = IV;


            CryptoStream cs = new CryptoStream(ms,
                                               alg.CreateEncryptor(), CryptoStreamMode.Write);


            cs.Write(clearData, 0, clearData.Length);


            cs.Close();


            byte[] encryptedData = ms.ToArray();

            return(encryptedData);
        }
Example #5
0
        private void Crypt_Click(object sender, RoutedEventArgs e)
        {
            switch (algorithmNumber)
            {
            case 0: { Encryption(aes.CreateEncryptor(aes.Key, aes.IV)); break; }

            case 1: { Encryption(des.CreateEncryptor(des.Key, des.IV)); break; }

            case 2: { Encryption(rc2.CreateEncryptor(rc2.Key, rc2.IV)); break; }
            }
        }
Example #6
0
        // RC2 encrypt data
        public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
        {
            FileStream   fStream = File.Open(FileName, FileMode.OpenOrCreate);
            RC2          RC2alg  = RC2.Create();
            CryptoStream cStream = new CryptoStream(fStream, RC2alg.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
            StreamWriter sWriter = new StreamWriter(cStream);

            sWriter.WriteLine(Data);
            sWriter.Close();
            cStream.Close();
            fStream.Close();
        }
Example #7
0
 /// <summary>
 /// 加密方法
 /// </summary>
 /// <param name="Source">待加密的串</param>
 /// <returns>经过加密的串</returns>
 public string Encrypt(string Source)
 {
     try
     {
         byte[]       bytIn = UTF8Encoding.UTF8.GetBytes(Source);
         MemoryStream ms    = new MemoryStream();
         rc.Key = GetLegalKey();
         rc.IV  = GetLegalIV();
         ICryptoTransform encrypto = rc.CreateEncryptor();
         CryptoStream     cs       = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
         cs.Write(bytIn, 0, bytIn.Length);
         cs.FlushFinalBlock();
         ms.Close();
         byte[] bytOut = ms.ToArray();
         return(Convert.ToBase64String(bytOut));
     }
     catch (Exception ex)
     {
         throw new Exception("在文件加密的时候出现错误!错误提示:  " + ex.Message);
     }
 }
Example #8
0
        public byte[] Encrypt(byte[] plainTextBytes)
        {
            byte[]       Key     = Encoding.UTF8.GetBytes(RC2Key);
            byte[]       IV      = Encoding.UTF8.GetBytes(RC2IV);
            MemoryStream mStream = new MemoryStream();
            RC2          RC2alg  = RC2.Create();
            CryptoStream cStream = new CryptoStream(mStream, RC2alg.CreateEncryptor(Key, IV), CryptoStreamMode.Write);

            cStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cStream.FlushFinalBlock();
            byte[] cyperTextBytes = mStream.ToArray();
            cStream.Close();
            mStream.Close();
            return(cyperTextBytes);
        }
Example #9
0
        public CodySecurityHelper2(string key = CodySecurityHelper2.DefaultKey, string iv = CodySecurityHelper2.DefaultIV)
        {
            this.Key = key;
            this.IV  = iv;
            RC2 rc = RC2.Create();

            key = key.PadLeft(16, ' ');
            key = key.Substring(key.Length - 16, 16);

            iv = iv.PadLeft(8, ' ');
            iv = iv.Substring(iv.Length - 8, 8);

            this.Encryptor = rc.CreateEncryptor(Encoding.Default.GetBytes(key), Encoding.Default.GetBytes(iv));
            this.Decryptor = rc.CreateDecryptor(Encoding.Default.GetBytes(key), Encoding.Default.GetBytes(iv));
        }
Example #10
0
        public static byte[] RC2Encrypt(byte[] clearData, string Password)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, MySalt);
            MemoryStream        ms  = new MemoryStream();
            RC2 alg = RC2.Create();

            alg.Key = pdb.GetBytes(8);
            alg.IV  = pdb.GetBytes(8);
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(clearData, 0, clearData.Length);
            cs.Close();
            byte[] encryptedData = ms.ToArray();
            return(encryptedData);
        }
Example #11
0
 public static void RC2ExplicitEncryptorDecryptor_WithIV()
 {
     using (RC2 alg = RC2Factory.Create())
     {
         alg.Padding = PaddingMode.PKCS7;
         alg.Mode    = CipherMode.CBC;
         using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), s_randomIv_64.HexToByteArray()))
         {
             byte[] plainText1      = s_multiBlockString.HexToByteArray();
             byte[] cipher1         = encryptor.Transform(plainText1);
             byte[] expectedCipher1 = (
                 "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
                 "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray();
             Assert.Equal <byte>(expectedCipher1, cipher1);
         }
     }
 }
Example #12
0
        public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
        {
            using (RC2 alg = RC2Factory.Create())
                using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
                {
                    // 1 block, plus maybe three bytes
                    int    outputPadding = blockAlignedOutput ? 0 : 3;
                    byte[] output        = new byte[alg.BlockSize / 8 + outputPadding];
                    // 3 blocks of 0x00
                    byte[] input = new byte[3 * (alg.BlockSize / 8)];

                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => xform.TransformBlock(input, 0, input.Length, output, 0));

                    Assert.Equal(new byte[output.Length], output);
                }
        }
Example #13
0
 public static void RC2ExplicitEncryptorDecryptor_NoIV()
 {
     using (RC2 alg = RC2Factory.Create())
     {
         alg.Padding = PaddingMode.PKCS7;
         alg.Mode    = CipherMode.ECB;
         using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), null))
         {
             byte[] plainText1      = s_multiBlockString.HexToByteArray();
             byte[] cipher1         = encryptor.Transform(plainText1);
             byte[] expectedCipher1 = (
                 "F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" +
                 "620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721AEB21E183555CE07").HexToByteArray();
             Assert.Equal <byte>(expectedCipher1, cipher1);
         }
     }
 }
Example #14
0
    public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
    {
        try
        {
            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream();

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(mStream,
                                                    RC2alg.CreateEncryptor(Key, IV),
                                                    CryptoStreamMode.Write);

            // Convert the passed string to a byte array.
            byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

            // Write the byte array to the crypto stream and flush it.
            cStream.Write(toEncrypt, 0, toEncrypt.Length);
            cStream.FlushFinalBlock();

            // Get an array of bytes from the
            // MemoryStream that holds the
            // encrypted data.
            byte[] ret = mStream.ToArray();

            // Close the streams.
            cStream.Close();
            mStream.Close();

            // Return the encrypted buffer.
            return(ret);
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return(null);
        }
    }
Example #15
0
        private string RC2Encrypt(byte[] clearBytes, string key)
        {
            string EncryptionKey = key.Substring(0, 8);
            string clearText;

            using (RC2 encryptor = RC2.Create())
            {
                encryptor.Key = ASCIIEncoding.ASCII.GetBytes(EncryptionKey);
                encryptor.IV  = ASCIIEncoding.ASCII.GetBytes(EncryptionKey);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return(clearText);
        }
Example #16
0
        private void RC2Code_Click(object sender, EventArgs e) // кодирование с помощью библиотеки RC2
        {
            string MainText = MainTextBox.Text;                // получение текста из текстового окна
            string KeyText  = KeyTextBox.Text;                 // получение ключа из текстового окна
            RC2    RC2alg   = RC2.Create();                    // создание экземпляра RС2

            byte[]       toEncrypt = new UTF8Encoding().GetBytes(MainText);
            byte[]       KeyByte   = new UTF8Encoding().GetBytes(KeyText);
            byte[]       IV        = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            MemoryStream mStream   = new MemoryStream();                                                                     // поток с памятью в качестве резервного хранилища
            CryptoStream CodeRC2   = new CryptoStream(mStream, RC2alg.CreateEncryptor(KeyByte, IV), CryptoStreamMode.Write); // поток кодирующий информацию с заданным ключем и вектором

            CodeRC2.Write(toEncrypt, 0, toEncrypt.Length);                                                                   // будут закодированы все элементы
            CodeRC2.FlushFinalBlock();                                                                                       // обновление данных и очистка буфера
            byte[] ret        = mStream.ToArray();
            string EncryptMes = Convert.ToBase64String(ret);

            CodeTextBox.Text = EncryptMes;
            CodeRC2.Close(); // закрытие кодирующего потока
            mStream.Close(); // закрытие потока с памятью
        }
Example #17
0
        private void encode_RC2_CBF_Click(object sender, EventArgs e)
        {
            DateTime then = DateTime.Now;
            String   Data = input7.Text;

            try
            {
                MemoryStream mStream = new MemoryStream();

                RC2 alg = RC2.Create();
                alg.GenerateKey();
                Key = alg.Key;
                alg.GenerateIV();
                IV = alg.IV;

                CryptoStream cStream = new CryptoStream(mStream,
                                                        alg.CreateEncryptor(Key, IV),
                                                        CryptoStreamMode.Write);

                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

                cStream.Write(toEncrypt, 0, toEncrypt.Length);
                cStream.FlushFinalBlock();

                byte[] ret = mStream.ToArray();

                cStream.Close();
                mStream.Close();

                cipherbytes = ret;
                input8.Text = Encoding.UTF8.GetString(cipherbytes);
                delta4.Text = (DateTime.Now - then).TotalSeconds.ToString() + " сек";
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", ex.Message);
                return;
            }
        }
        static byte[] EncryptRC2(string plainText, byte[] Key, byte[] IV)
        {
            byte[] encrypted;

            using (RC2 rc2 = RC2.Create())
            {
                ICryptoTransform encryptor = rc2.CreateEncryptor(Key, IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                            sw.Write(plainText);

                        encrypted = ms.ToArray();
                    }
                }
            }

            return(encrypted);
        }
Example #19
0
        public static void RC2ReuseEncryptorDecryptor()
        {
            using (RC2 alg = RC2Factory.Create())
            {
                alg.Key     = s_randomKey_64.HexToByteArray();
                alg.IV      = s_randomIv_64.HexToByteArray();
                alg.Padding = PaddingMode.PKCS7;
                alg.Mode    = CipherMode.CBC;

                using (ICryptoTransform encryptor = alg.CreateEncryptor())
                    using (ICryptoTransform decryptor = alg.CreateDecryptor())
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            byte[] plainText1      = s_multiBlockString.HexToByteArray();
                            byte[] cipher1         = encryptor.Transform(plainText1);
                            byte[] expectedCipher1 = (
                                "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
                                "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray();
                            Assert.Equal <byte>(expectedCipher1, cipher1);

                            byte[] decrypted1         = decryptor.Transform(cipher1);
                            byte[] expectedDecrypted1 = s_multiBlockString.HexToByteArray();
                            Assert.Equal <byte>(expectedDecrypted1, decrypted1);

                            byte[] plainText2      = s_multiBlockString_8.HexToByteArray();
                            byte[] cipher2         = encryptor.Transform(plainText2);
                            byte[] expectedCipher2 = (
                                "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67F6056044F15B5C7ED" +
                                "4FAB086053D7DC458C206145AE9655F1590C590FBDE76365FA488CADBCDA67B325A35E7CCBC1B9A15E5EBE2879C7AEC2").HexToByteArray();
                            Assert.Equal <byte>(expectedCipher2, cipher2);

                            byte[] decrypted2         = decryptor.Transform(cipher2);
                            byte[] expectedDecrypted2 = s_multiBlockString_8.HexToByteArray();
                            Assert.Equal <byte>(expectedDecrypted2, decrypted2);
                        }
                    }
            }
        }
Example #20
0
    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the FileStream
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                                                    RC2alg.CreateEncryptor(Key, IV),
                                                    CryptoStreamMode.Write);

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter(cStream);

            // Write the data to the stream
            // to encrypt it.
            sWriter.WriteLine(Data);

            // Close the streams and
            // close the file.
            sWriter.Close();
            cStream.Close();
            fStream.Close();
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
        }
    }
Example #21
0
        public static void EncryptWithLargeOutputBuffer(bool blockAlignedOutput)
        {
            using (RC2 alg = RC2Factory.Create())
                using (ICryptoTransform xform = alg.CreateEncryptor())
                {
                    // 8 blocks, plus maybe three bytes
                    int    outputPadding = blockAlignedOutput ? 0 : 3;
                    byte[] output        = new byte[alg.BlockSize + outputPadding];
                    // 2 blocks of 0x00
                    byte[] input        = new byte[alg.BlockSize / 4];
                    int    outputOffset = 0;

                    outputOffset += xform.TransformBlock(input, 0, input.Length, output, outputOffset);
                    byte[] overflow = xform.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                    Buffer.BlockCopy(overflow, 0, output, outputOffset, overflow.Length);
                    outputOffset += overflow.Length;

                    Assert.Equal(3 * (alg.BlockSize / 8), outputOffset);
                    string outputAsHex = output.ByteArrayToHex();
                    Assert.NotEqual(new string('0', outputOffset * 2), outputAsHex.Substring(0, outputOffset * 2));
                    Assert.Equal(new string('0', (output.Length - outputOffset) * 2), outputAsHex.Substring(outputOffset * 2));
                }
        }
Example #22
0
        public static void EncryptorReuse_LeadsToSameResults(CipherMode cipherMode, int feedbackSize)
        {
            // AppleCCCryptor does not allow calling Reset on CFB cipher.
            // this test validates that the behavior is taken into consideration.
            var input = "b72606c98d8e4fabf08839abf7a0ac61".HexToByteArray();

            using (RC2 rc2 = RC2Factory.Create())
            {
                rc2.Mode = cipherMode;

                if (feedbackSize > 0)
                {
                    rc2.FeedbackSize = feedbackSize;
                }

                using (ICryptoTransform transform = rc2.CreateEncryptor())
                {
                    byte[] output1 = transform.TransformFinalBlock(input, 0, input.Length);
                    byte[] output2 = transform.TransformFinalBlock(input, 0, input.Length);

                    Assert.Equal(output1, output2);
                }
            }
        }
        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            switch (this.algorithmID)
            {
            case EncryptionAlgorithm.Des:
                DES des = (DES) new DESCryptoServiceProvider();
                des.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    this.encKey = des.Key;
                }
                else
                {
                    des.Key     = bytesKey;
                    this.encKey = des.Key;
                }
                if (this.initVec == null)
                {
                    this.initVec = des.IV;
                }
                else
                {
                    des.IV = this.initVec;
                }
                return(des.CreateEncryptor());

            case EncryptionAlgorithm.Rc2:
                RC2 rc2 = (RC2) new RC2CryptoServiceProvider();
                rc2.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    this.encKey = rc2.Key;
                }
                else
                {
                    rc2.Key     = bytesKey;
                    this.encKey = rc2.Key;
                }
                if (this.initVec == null)
                {
                    this.initVec = rc2.IV;
                }
                else
                {
                    rc2.IV = this.initVec;
                }
                return(rc2.CreateEncryptor());

            case EncryptionAlgorithm.Rijndael:
                Rijndael rijndael = (Rijndael) new RijndaelManaged();
                rijndael.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    this.encKey = rijndael.Key;
                }
                else
                {
                    rijndael.Key = bytesKey;
                    this.encKey  = rijndael.Key;
                }
                if (this.initVec == null)
                {
                    this.initVec = rijndael.IV;
                }
                else
                {
                    rijndael.IV = this.initVec;
                }
                return(rijndael.CreateEncryptor());

            case EncryptionAlgorithm.TripleDes:
                TripleDES tripleDes = (TripleDES) new TripleDESCryptoServiceProvider();
                tripleDes.Mode = CipherMode.CBC;
                if (bytesKey == null)
                {
                    this.encKey = tripleDes.Key;
                }
                else
                {
                    tripleDes.Key = bytesKey;
                    this.encKey   = tripleDes.Key;
                }
                if (this.initVec == null)
                {
                    this.initVec = tripleDes.IV;
                }
                else
                {
                    tripleDes.IV = this.initVec;
                }
                return(tripleDes.CreateEncryptor());

            default:
                throw new CryptographicException("Algorithm ID '" + (object)this.algorithmID + "' not supported.");
            }
        }
Example #24
0
        public static string Encrypt(CryptoType cryptoMethod, string txt, string cryptoKey, string cryptoIV)
        {
            string retValue = String.Empty;

            try
            {
                byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
                byte[] iv  = Encoding.UTF8.GetBytes(cryptoIV);

                ICryptoTransform cTransform = null;

                switch (cryptoMethod)
                {
                case CryptoType.aes:
                    using (Aes aes = Aes.Create())
                    {
                        if ((checkSize(aes.Key.Length, key.Length).Equals(true)) & (checkSize(aes.IV.Length, iv.Length).Equals(true)))
                        {
                            cTransform = aes.CreateEncryptor(key, iv);
                        }
                    }
                    break;

                case CryptoType.des:
                    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                    {
                        if ((checkSize(des.Key.Length, key.Length).Equals(true)) & (checkSize(des.IV.Length, iv.Length).Equals(true)))
                        {
                            cTransform = des.CreateEncryptor(key, iv);
                        }
                    }
                    break;

                case CryptoType.rc2:
                    using (RC2 rc2 = RC2.Create())
                    {
                        if ((checkSize(rc2.Key.Length, key.Length).Equals(true)) & (checkSize(rc2.IV.Length, iv.Length).Equals(true)))
                        {
                            cTransform = rc2.CreateEncryptor(key, iv);
                        }
                    }
                    break;

                case CryptoType.rijndael:
                    using (Rijndael rij = Rijndael.Create())
                    {
                        if ((checkSize(rij.Key.Length, key.Length).Equals(true)) & (checkSize(rij.IV.Length, iv.Length).Equals(true)))
                        {
                            cTransform = rij.CreateEncryptor(key, iv);
                        }
                    }
                    break;

                case CryptoType.tripledes:
                    using (TripleDESCryptoServiceProvider triDES = new TripleDESCryptoServiceProvider())
                    {
                        if ((checkSize(triDES.Key.Length, key.Length).Equals(true)) & (checkSize(triDES.IV.Length, iv.Length).Equals(true)))
                        {
                            cTransform = triDES.CreateEncryptor(key, iv);
                        }
                    }
                    break;
                }
                if (cTransform != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, cTransform, CryptoStreamMode.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(cs))
                            {
                                sw.Write(txt);
                            }
                            retValue = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                    cTransform.Dispose();
                }
                else
                {
                    throw new CryptographicException();
                }
            }
            catch (CryptographicException cex)
            {
                throw new ApplicationException("Cryptographic Encryption Exception", cex);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Encrypt Exception", ex);
            }
            return(retValue);
        }
Example #25
0
        public static ICryptoTransform CreateEncryptor(RC2 provider, string key, int keySize)
        {
            var kv = CreateKeyVector(key, keySize);

            return(provider.CreateEncryptor(kv.First, kv.Second));
        }