コード例 #1
0
        /// <summary>
        ///     returns the specific symmetric algorithm acc. to the cryptotype
        /// </summary>
        /// <returns>SymmetricAlgorithm</returns>
        private SymmetricAlgorithm selectAlgorithm()
        {
            SymmetricAlgorithm sa;

            switch (mCryptoType)
            {
            case CryptoTypes.EncTypeDes:
                sa = DES.Create();
                break;

            case CryptoTypes.EncTypeRc2:
                sa = RC2.Create();
                break;

            case CryptoTypes.EncTypeRijndael:
                sa = Rijndael.Create();
                break;

            case CryptoTypes.EncTypeTripleDes:
                sa = TripleDES.Create();
                break;

            default:
                sa = TripleDES.Create();
                break;
            }
            return(sa);
        }
コード例 #2
0
        private void SymmetricAlgorithmChanged(object sender, EventArgs e)
        {
            var rb = sender as RadioButton;

            if (!rb.Checked)
            {
                return;
            }

            switch (rb.Text)
            {
            case "DES":
                this.koder.SymmetricAlgorithm = DES.Create();
                break;

            case "RC2":
                this.koder.SymmetricAlgorithm = RC2.Create();
                break;

            case "Triple DES":
                this.koder.SymmetricAlgorithm = TripleDES.Create();
                break;

            case "Rijndael":
                this.koder.SymmetricAlgorithm = Rijndael.Create();
                break;
            }

            this.GenerateKey(sender, e);
            this.GenerateVI(sender, e);
        }
コード例 #3
0
        /// <summary>
        ///		returns the specific symmetric algorithm acc. to the cryptotype
        /// </summary>
        /// <returns>SymmetricAlgorithm</returns>
        private SymmetricAlgorithm selectAlgorithm()
        {
            SymmetricAlgorithm SA;

            switch (mCryptoType)
            {
            case CryptoTypes.encTypeDES:
                SA = DES.Create();
                break;

            case CryptoTypes.encTypeRC2:
                SA = RC2.Create();
                break;

            case CryptoTypes.encTypeRijndael:
                SA = Rijndael.Create();
                break;

            case CryptoTypes.encTypeTripleDES:
                SA = TripleDES.Create();
                break;

            default:
                SA = TripleDES.Create();
                break;
            }
            return(SA);
        }
コード例 #4
0
        void AlgorithmChanged(object sender, RoutedEventArgs e)
        {
            algorithmNumber = Algorithms.SelectedIndex;
            switch (algorithmNumber)
            {
            case 0:
            {
                aes      = Aes.Create();
                Key.Text = ArrayToString(aes.Key);
                IV.Text  = ArrayToString(aes.IV);
                break;
            }

            case 1:
            {
                des      = DES.Create();
                Key.Text = ArrayToString(des.Key);
                IV.Text  = ArrayToString(des.IV);
                break;
            }

            case 2:
            {
                rc2      = RC2.Create();
                Key.Text = ArrayToString(rc2.Key);
                IV.Text  = ArrayToString(rc2.IV);
                break;
            }
            }
        }
コード例 #5
0
        /// <summary> 获取对称加密方法 </summary>
        private static SymmetricAlgorithm GetSymmetricAlgorithm(SymmetricFormat symmetricFormat)
        {
            SymmetricAlgorithm algorithm;

            switch (symmetricFormat)
            {
            case SymmetricFormat.DES:
                algorithm = DES.Create();
                break;

            case SymmetricFormat.TripleDES:
                algorithm = TripleDES.Create();
                break;

            case SymmetricFormat.RC2:
                algorithm = RC2.Create();
                break;

            case SymmetricFormat.Rijndael:
                algorithm = Rijndael.Create();
                break;

            case SymmetricFormat.AES:
                algorithm = Aes.Create();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(symmetricFormat), symmetricFormat, null);
            }

            return(algorithm);
        }
コード例 #6
0
        /// <summary>
        /// Instantiates a new symmetric encryption object using the specified provider.
        /// </summary>
        public SymmetricCrypto(Provider provider, bool useDefaultInitializationVector)
        {
            switch (provider)
            {
            case Provider.DES:
                m_SymmAlgorithm = DES.Create();
                break;

            case Provider.RC2:
                m_SymmAlgorithm = RC2.Create();
                break;

            case Provider.Rijndael:
                m_SymmAlgorithm = Aes.Create();
                break;

            case Provider.TripleDES:
                m_SymmAlgorithm = TripleDES.Create();
                break;
            }

            //-- make sure key and IV are always set, no matter what
            this.Key = RandomKey();
            if (useDefaultInitializationVector)
            {
                this.IntializationVector = new ByteArray(DefaultIntializationVector);
            }
            else
            {
                this.IntializationVector = RandomInitializationVector();
            }
        }
コード例 #7
0
        public static SymmetricAlgorithm CreateCipher(CipherIdentifier identifier, int keySize, int blockSize, CipherMode mode)
        {
            switch (identifier)
            {
            case CipherIdentifier.RC4:
                return(new RC4Managed());

            case CipherIdentifier.DES3:
                return(InitCipher(TripleDES.Create(), keySize, blockSize, mode));

#if NET45 || NETSTANDARD2_0
            case CipherIdentifier.RC2:
                return(InitCipher(RC2.Create(), keySize, blockSize, mode));

            case CipherIdentifier.DES:
                return(InitCipher(DES.Create(), keySize, blockSize, mode));

            case CipherIdentifier.AES:
                return(InitCipher(new RijndaelManaged(), keySize, blockSize, mode));
#else
            case CipherIdentifier.AES:
                return(InitCipher(Aes.Create(), keySize, blockSize, mode));
#endif
            }

            throw new InvalidOperationException("Unsupported encryption method: " + identifier.ToString());
        }
コード例 #8
0
        /// <summary> 获取对称加密方法 </summary>
        private static SymmetricAlgorithm GetSymmetricAlgorithm(SymmetricFormat symmetricFormat)
        {
            SymmetricAlgorithm algorithm = null;

            switch (symmetricFormat)
            {
            case SymmetricFormat.DES:
                algorithm = DES.Create();
                break;

            case SymmetricFormat.TripleDES:
                algorithm = TripleDES.Create();
                break;

            case SymmetricFormat.RC2:
                algorithm = RC2.Create();
                break;

            case SymmetricFormat.Rijndael:
                algorithm = Rijndael.Create();
                break;

            case SymmetricFormat.AES:
                algorithm = Aes.Create();
                break;
            }

            return(algorithm);
        }
コード例 #9
0
    public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
    {
        try
        {
            // Create a new MemoryStream using the passed
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

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

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                                                      RC2alg.CreateDecryptor(Key, IV),
                                                      CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it.
            return(new ASCIIEncoding().GetString(fromEncrypt));
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return(null);
        }
    }
コード例 #10
0
    static void Main()
    {
        try
        {
            // Create a new RC2 object to generate a key
            // and initialization vector (IV).
            RC2 RC2alg = RC2.Create();

            // Create a string to encrypt.
            string sData = "Here is some data to encrypt.";

            // Encrypt the string to an in-memory buffer.
            byte[] Data = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV);

            // Decrypt the buffer back to a string.
            string Final = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV);

            // Display the decrypted string to the console.
            Console.WriteLine(Final);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
コード例 #11
0
ファイル: RC2Test.cs プロジェクト: pmq20/mono_forked
        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);
            }
        }
コード例 #12
0
        public MyCryptography()
        {
            try
            {
                encryptAlgs    = new SymmetricAlgorithm[5];
                encryptAlgs[0] = Rijndael.Create();
                encryptAlgs[1] = Aes.Create();
                encryptAlgs[2] = DES.Create();
                encryptAlgs[3] = TripleDES.Create();
                encryptAlgs[4] = RC2.Create();

                encryptAlg = encryptAlgs[0];

                decryptAlgs    = new SymmetricAlgorithm[5];
                decryptAlgs[0] = Rijndael.Create();
                decryptAlgs[1] = Aes.Create();
                decryptAlgs[2] = DES.Create();
                decryptAlgs[3] = TripleDES.Create();
                decryptAlgs[4] = RC2.Create();

                decryptAlg = decryptAlgs[0];
            }
            catch (Exception e)
            {
                throw;
            }
        }
コード例 #13
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);
        }
コード例 #14
0
        // Decrypt a byte array into a byte array using a key and an IV
        private static byte[] Decrypt(byte[] cipherData,
                                      byte[] Key, byte[] IV)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes
            MemoryStream ms = new MemoryStream();


            RC2 alg = RC2.Create();

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

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


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


            cs.Close();


            byte[] decryptedData = ms.ToArray();

            return(decryptedData);
        }
コード例 #15
0
    static void Main()
    {
        try
        {
            // Create a new RC2 object to generate a key
            // and initialization vector (IV).  Specify one
            // of the recognized simple names for this
            // algorithm.
            RC2 RC2alg = RC2.Create("RC2");

            // Create a string to encrypt.
            string sData    = "Here is some data to encrypt.";
            string FileName = "CText.txt";

            // Encrypt text to a file using the file name, key, and IV.
            EncryptTextToFile(sData, FileName, RC2alg.Key, RC2alg.IV);

            // Decrypt the text from a file using the file name, key, and IV.
            string Final = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.IV);

            // Display the decrypted string to the console.
            Console.WriteLine(Final);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
コード例 #16
0
ファイル: Crypto.cs プロジェクト: ApoloAGP/solAGP
        private SymmetricAlgorithm SeleccionarAlgoritmo()
        {
            SymmetricAlgorithm Sa;

            switch (_mEncriptacion)
            {
            case TipoEncriptacion.TipoDes:
                Sa = DES.Create();
                break;

            case TipoEncriptacion.TipoRec:
                Sa = RC2.Create();
                break;

            case TipoEncriptacion.TipoRijndael:
                Sa = Rijndael.Create();
                break;

            case TipoEncriptacion.TipoTripleDes:
                Sa = TripleDES.Create();
                break;

            default:
                Sa = TripleDES.Create();
                break;
            }
            return(Sa);
        }
コード例 #17
0
        private SymmetricAlgorithm CreateAlgorithm(string algorithmName)
        {
#if !NETSTANDARD
            return(SymmetricAlgorithm.Create(algorithmName));
#endif
            switch (algorithmName.ToUpper())
            {
            case "AES":
                return(Aes.Create());

            case "DES":
                return(DES.Create());

            case "RC2":
                return(RC2.Create());

            case "RIJNDAEL":
                return(Rijndael.Create());

            case "TRIPLEDES":
                return(TripleDES.Create());

            default:
                return(null);
            }
        }
コード例 #18
0
        private static SymmetricAlgorithm GetSymmetricAlgorithm(CryptoKind kind)
        {
            SymmetricAlgorithm algorithm = null;

            switch (kind)
            {
            case CryptoKind.DES:
                algorithm = DES.Create();
                break;

            case CryptoKind.TripleDES:
                algorithm = TripleDES.Create();
                break;

            case CryptoKind.RC2:
                algorithm = RC2.Create();
                break;

            case CryptoKind.Rijndael:
                algorithm = Rijndael.Create();
                break;

            case CryptoKind.AES:
                algorithm = Aes.Create();
                break;
            }

            return(algorithm);
        }
コード例 #19
0
        public static System.Security.Cryptography.SymmetricAlgorithm CreateSymmetricAlgorithm(
            this SymmetricAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case SymmetricAlgorithm.Aes:
                return(Aes.Create());

            case SymmetricAlgorithm.DES:
                return(DES.Create());

            case SymmetricAlgorithm.RC2:
                return(RC2.Create());

            case SymmetricAlgorithm.Rijndael:
                return(Rijndael.Create());

            case SymmetricAlgorithm.TripleDES:
                return(TripleDES.Create());

            default:
                throw new ArgumentOutOfRangeException("algorithm", algorithm,
                                                      $@"Invalid SymmetricAlgorithm. Valid values are: {
                            string.Join(", ", Enum.GetValues(typeof(SymmetricAlgorithm))
                                .Cast<SymmetricAlgorithm>().Select(x => x.ToString()))}.");
            }
        }
コード例 #20
0
        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!");
            }
        }
コード例 #21
0
        private void rc2Decryption(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);

                byte[] input  = File.ReadAllBytes(this.InputTextBox.Text);
                string output = null;

                ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key, rc2.IV);

                using (MemoryStream msDecrypt = new MemoryStream(input))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            output = srDecrypt.ReadToEnd();
                        }
                    }
                }

                File.WriteAllText(this.OutputTextBox.Text, output);
                MessageBox.Show("Succesfuly decrypted!");
            }
        }
コード例 #22
0
 static SymmetricAlgorithmsManager()
 {
     Algorithms[Algorithm.Aes]       = Aes.Create();
     Algorithms[Algorithm.DES]       = DES.Create();
     Algorithms[Algorithm.RC2]       = RC2.Create();
     Algorithms[Algorithm.Rijndael]  = Rijndael.Create();
     Algorithms[Algorithm.TripleDES] = TripleDES.Create();
 }
コード例 #23
0
 static void InSecureObj()
 {
     var tripleDES  = TripleDES.Create();
     var tripleDES1 = Create();
     var tripleDES2 = tdes.Create();
     var simpleDES  = DES.Create();
     var rC2        = RC2.Create();
 }
コード例 #24
0
        public override void Run()
        {
            try {
                using (var inputStream = new FileStream(InputFileName, FileMode.Open))
                    using (var keyStream = new FileStream(KeyFileName, FileMode.Open))
                        using (var outputStream = new FileStream(OutputFileName, FileMode.Create)) {
                            using (var sr = new StreamReader(keyStream)) {
                                string ivString  = sr.ReadLine();
                                string keyString = sr.ReadLine();
                                if (ivString == null || keyString == null)
                                {
                                    throw new EnigmaException("Invalid key or IV");
                                }

                                byte[] iv  = Convert.FromBase64String(ivString);
                                byte[] key = Convert.FromBase64String(keyString);

                                switch (Method)
                                {
                                case EncryptionMethod.Aes: {
                                    using (var aes = Aes.Create()) {
                                        Decrypt(inputStream, outputStream, aes, key, iv);
                                    }
                                    break;
                                }

                                case EncryptionMethod.Des: {
                                    using (var des = DES.Create()) {
                                        Decrypt(inputStream, outputStream, des, key, iv);
                                    }
                                    break;
                                }

                                case EncryptionMethod.Rc2:
                                    using (var rc2 = RC2.Create()) {
                                        Decrypt(inputStream, outputStream, rc2, key, iv);
                                    }
                                    break;

                                case EncryptionMethod.Rijndael: {
                                    using (var rijndael = Rijndael.Create()) {
                                        Decrypt(inputStream, outputStream, rijndael, key, iv);
                                    }
                                    break;
                                }

                                default: throw new EnigmaException("Unknown encryption method");
                                }
                            }
                        }
            }
            catch (FileNotFoundException e) {
                throw new EnigmaException($"decrypt: file not found: {e.FileName}");
            }
            catch (IOException e) {
                throw new EnigmaException($"decrypt: {e.Message}");
            }
        }
コード例 #25
0
        static string EncryptRC2Managed(string raw)
        {
            byte[] encrypted;

            using (RC2 rc2 = RC2.Create())
                encrypted = EncryptRC2(raw, rc2.Key, rc2.IV);

            return(Encoding.UTF8.GetString(encrypted));
        }
コード例 #26
0
        /// <summary>
        ///     Выполняет шифрование сообщения алгоритмом RC2
        /// </summary>
        ///
        /// <param name="message">
        ///     Шифруемое сообщение
        /// </param>
        ///
        /// <param name="key">
        ///     Ключ шифрования
        /// </param>
        ///
        /// <param name="IV">
        ///     Вектор шифрования
        /// </param>
        ///
        /// <returns>
        ///     Возвращает сообщение в зашифрованном виде
        /// </returns>
        public static byte[] RC2Encrypt(string message, string key, string IV)
        {
            var keyToBytes = StringToBytes(key, 16);
            var IVToBytes  = StringToBytes(IV, 8);

            byte[] encrypted = EncryptStringToBytes(message, keyToBytes, IVToBytes, RC2.Create());

            return(encrypted);
        }
コード例 #27
0
ファイル: ManagedPal.cs プロジェクト: pedrobsaila/runtime
        private static SymmetricAlgorithm OpenAlgorithm(string algorithmIdentifier)
        {
            Debug.Assert(algorithmIdentifier != null);

            SymmetricAlgorithm alg;

            switch (algorithmIdentifier)
            {
            case Oids.Rc2Cbc:
                if (!Helpers.IsRC2Supported)
                {
                    throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(RC2)));
                }
#pragma warning disable CA5351
                alg = RC2.Create();
#pragma warning restore CA5351
                break;

            case Oids.DesCbc:
#pragma warning disable CA5351
                alg = DES.Create();
#pragma warning restore CA5351
                break;

            case Oids.TripleDesCbc:
#pragma warning disable CA5350
                alg = TripleDES.Create();
#pragma warning restore CA5350
                break;

            case Oids.Aes128Cbc:
                alg         = Aes.Create();
                alg.KeySize = 128;
                break;

            case Oids.Aes192Cbc:
                alg         = Aes.Create();
                alg.KeySize = 192;
                break;

            case Oids.Aes256Cbc:
                alg         = Aes.Create();
                alg.KeySize = 256;
                break;

            default:
                throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier);
            }

            // These are the defaults, but they're restated here for clarity.
            alg.Padding = PaddingMode.PKCS7;
            alg.Mode    = CipherMode.CBC;
            return(alg);
        }
コード例 #28
0
ファイル: RC2Tests.cs プロジェクト: aik-jahoda/runtime
        public static void EnsureLegalSizesValuesIsolated()
        {
            new RC2LegalSizesBreaker().Dispose();

            using (RC2 rc2 = RC2.Create())
            {
                Assert.Equal(40, rc2.LegalKeySizes[0].MinSize);
                Assert.Equal(64, rc2.LegalBlockSizes[0].MinSize);

                rc2.Key = new byte[8];
            }
        }
コード例 #29
0
ファイル: TestRC2.cs プロジェクト: ForNeVeR/pnet
 // Test that the algorithm specific class cannot return
 // an object of another algorithm.
 public void TestRC2CreateOther()
 {
     try
     {
         RC2.Create("DES");
         Fail();
     }
     catch (InvalidCastException)
     {
         // Success case.
     }
 }
コード例 #30
0
ファイル: FrmSymmetric.cs プロジェクト: NewLifeX/XCoder
        private void btnRC22_Click(Object sender, EventArgs e)
        {
            var buf  = GetSource();
            var pass = GetPass();

            var mode    = (CipherMode)Enum.Parse(typeof(CipherMode), cmbCipher.SelectedItem + "");
            var padding = (PaddingMode)Enum.Parse(typeof(PaddingMode), cmbPadding.SelectedItem + "");

            buf = RC2.Create().Decrypt(buf, pass, mode, padding);

            SetResult(buf);
        }