Beispiel #1
0
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
            {
                throw new TlsFatalAlert(80);
            }
            this.context = context;
            byte[]       key           = TlsUtilities.CalculateKeyBlock(context, 64);
            KeyParameter keyParameter  = new KeyParameter(key, 0, 32);
            KeyParameter keyParameter2 = new KeyParameter(key, 32, 32);

            this.encryptCipher = new ChaChaEngine(20);
            this.decryptCipher = new ChaChaEngine(20);
            KeyParameter parameters;
            KeyParameter parameters2;

            if (context.IsServer)
            {
                parameters  = keyParameter2;
                parameters2 = keyParameter;
            }
            else
            {
                parameters  = keyParameter;
                parameters2 = keyParameter2;
            }
            byte[] iv = new byte[8];
            this.encryptCipher.Init(true, new ParametersWithIV(parameters, iv));
            this.decryptCipher.Init(false, new ParametersWithIV(parameters2, iv));
        }
Beispiel #2
0
        /// <summary>
        /// Decrypt the given data using the Chacha engine.
        /// </summary>
        /// <param name="input">Ciphertext data.</param>
        /// <param name="key">Chacha decryption key.</param>
        /// <returns>Decrypted (cleartext) data or null in the event of a failure.</returns>
        public byte[] decryptWithChacha(byte[] input, byte[] key)
        {
            // Extract the nonce from the input
            byte[] nonce = input.Take(8).ToArray();

            // Generate the Chacha engine
            var parms  = new ParametersWithIV(new KeyParameter(key), nonce);
            var chacha = new ChaChaEngine(chacha_rounds);

            try
            {
                chacha.Init(false, parms);
            }
            catch (Exception e)
            {
                Logging.error(string.Format("Error in chacha decryption. {0}", e.ToString()));
                return(null);
            }

            // Create a buffer that will contain the decrypted output
            byte[] outData = new byte[input.Length - 8];

            // Decrypt the input data
            chacha.ProcessBytes(input, 8, input.Length - 8, outData, 0);

            // Return the decrypted data buffer
            return(outData);
        }
        /// <exception cref="IOException"></exception>
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.context = context;

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, 64);

            KeyParameter client_write_key = new KeyParameter(key_block, 0, 32);
            KeyParameter server_write_key = new KeyParameter(key_block, 32, 32);

            this.encryptCipher = new ChaChaEngine(20);
            this.decryptCipher = new ChaChaEngine(20);

            KeyParameter encryptKey, decryptKey;

            if (context.IsServer)
            {
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[8];

            this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, dummyNonce));
            this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, dummyNonce));
        }
        static byte[] EncryptStatic(byte[] src, byte[] iv = null)
        {
            var key = new byte[] {
                0xD3, 0x61, 0x57, 0x17, 0xE2, 0x16, 0x3F, 0x70, 0xAC, 0x69, 0x51, 0xB2, 0x7D, 0x7A, 0x0B, 0x86,
                0xD8, 0xE9, 0x3E, 0x16, 0xEA, 0xBF, 0x63, 0x2F, 0xDF, 0xBC, 0xC0, 0x0A, 0x1D, 0x3D, 0x62, 0xD6
            };


            if (iv == null)
            {
                iv = new byte[8];
                using (var rng = RandomNumberGenerator.Create())
                    rng.GetBytes(iv);
            }

            var cce = new ChaChaEngine();

            cce.Init(true, new ParametersWithIV(new KeyParameter(key), iv));

            var bsc    = new BufferedStreamCipher(cce);
            var output = new byte[src.Length + 8];

            Array.Copy(iv, output, 8);
            bsc.ProcessBytes(src, 0, src.Length, output, 8);
            return(output);
        }
Beispiel #5
0
        public byte[] Cloak()
        {
            Encode();

            byte[] outData = new byte[FullPacket.Length + 8];

            // Get our nonce
            Random rnd = new Random();

            byte[] nonce = new byte[8];
            rnd.NextBytes(nonce);
            // We can't have a leading 0 byte
            if (nonce [0] == 0)
            {
                nonce [0] = 1;
            }

            var parms  = new ParametersWithIV(new KeyParameter(cloakKey), nonce);
            var chacha = new ChaChaEngine(20);

            chacha.Init(true, parms);
            chacha.ProcessBytes(FullPacket, 0, FullPacket.Length, outData, 8);
            Buffer.BlockCopy(nonce, 0, outData, 0, 8);

            return(outData);
        }
Beispiel #6
0
        // Encrypt data using Chacha engine
        public byte[] encryptWithChacha(byte[] input, byte[] key)
        {
            // Create a buffer that will contain the encrypted output and an 8 byte nonce
            byte[] outData = new byte[input.Length + 8];

            // Generate the 8 byte nonce
            byte[] nonce = getSecureRandomBytes(8);

            // Prevent leading 0 to avoid edge cases
            if (nonce[0] == 0)
            {
                nonce[0] = 1;
            }

            // Generate the Chacha engine
            var parms  = new ParametersWithIV(new KeyParameter(key), nonce);
            var chacha = new ChaChaEngine(chacha_rounds);

            chacha.Init(true, parms);

            // Encrypt the input data while maintaing an 8 byte offset at the start
            chacha.ProcessBytes(input, 0, input.Length, outData, 8);

            // Copy the 8 byte nonce to the start of outData buffer
            Buffer.BlockCopy(nonce, 0, outData, 0, 8);

            // Return the encrypted data buffer
            return(outData);
        }
Beispiel #7
0
        /// <summary>
        /// Encrypt data with ChaCha20
        /// </summary>
        /// <param name="input">Input stream to encrypt</param>
        /// <param name="output">Output stream</param>
        /// <param name="key">Key</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="notifyProgression">Notify progression method</param>
        /// <param name="bufferSize">Buffer size</param>
        public static void Encrypt(Stream input, Stream output, byte[] key, byte[] nonce, Action <int> notifyProgression = null, int bufferSize = 4096)
        {
            ChaChaEngine     engine     = new ChaChaEngine();
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), nonce, 0, nonce.Length);

            engine.Init(true, parameters);

            int bytesRead;

            byte[] buffer = new byte[bufferSize];
            byte[] enc    = new byte[bufferSize];
            do
            {
                bytesRead = input.Read(buffer, 0, bufferSize);
                if (bytesRead > 0)
                {
                    engine.ProcessBytes(buffer, 0, bytesRead, enc, 0);
                    output.Write(enc, 0, bytesRead);

                    if (notifyProgression != null)
                    {
                        notifyProgression(bytesRead);
                    }
                }
            } while (bytesRead == bufferSize);
        }
Beispiel #8
0
        private void chachaTest1(
            int rounds,
            ICipherParameters parameters,
            string v0,
            string v192,
            string v256,
            string v448)
        {
            IStreamCipher salsa = new ChaChaEngine(rounds);

            byte[] buf = new byte[64];

            salsa.Init(true, parameters);

            for (int i = 0; i != 7; i++)
            {
                salsa.ProcessBytes(zeroes, 0, 64, buf, 0);
                switch (i)
                {
                case 0:
                    if (!AreEqual(buf, Hex.Decode(v0)))
                    {
                        mismatch("v0/" + rounds, v0, buf);
                    }
                    break;

                case 3:
                    if (!AreEqual(buf, Hex.Decode(v192)))
                    {
                        mismatch("v192/" + rounds, v192, buf);
                    }
                    break;

                case 4:
                    if (!AreEqual(buf, Hex.Decode(v256)))
                    {
                        mismatch("v256/" + rounds, v256, buf);
                    }
                    break;

                default:
                    // ignore
                    break;
                }
            }

            for (int i = 0; i != 64; i++)
            {
                buf[i] = salsa.ReturnByte(zeroes[i]);
            }

            if (!AreEqual(buf, Hex.Decode(v448)))
            {
                mismatch("v448", v448, buf);
            }
        }
        static byte[] Encrypt(byte[] src, byte[] key, byte[] iv)
        {
            var cce = new ChaChaEngine();

            cce.Init(true, new ParametersWithIV(new KeyParameter(key), iv));

            var bsc = new BufferedStreamCipher(cce);

            return(bsc.ProcessBytes(src));
        }
Beispiel #10
0
        internal static byte[] ChachaDecrypt(byte[] encrypted, byte[] key)
        {
            ChaChaEngine engine = new ChaChaEngine();
            var          iv     = new byte[ChachaKeySize / 2];

            Array.Copy(encrypted, iv, iv.Length);
            engine.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
            byte[] result = new byte[encrypted.Length - iv.Length];
            engine.ProcessBytes(encrypted, iv.Length, encrypted.Length - iv.Length, result, 0);
            return(result);
        }
        public EncryptorChaCha(bool encrypting, byte[] key, byte[] nonce)
        {
            Encrypting = encrypting;
            Key        = key;
            Nonce      = nonce;

            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(DefaultChaChaEncKey), DefaultChaChaEncNonce);

            Engine = new ChaChaEngine(20);
            Engine.Init(encrypting, parameters);
        }
Beispiel #12
0
        /// <summary>
        /// Decrypt data with ChaCha20
        /// </summary>
        /// <param name="data">Data to decrypt</param>
        /// <param name="key">Key</param>
        /// <param name="nonce">Nonce</param>
        /// <returns>Decrypted data</returns>
        public static byte[] Decrypt(byte[] data, byte[] key, byte[] nonce)
        {
            byte[] dec = new byte[data.Length];

            ChaChaEngine     engine     = new ChaChaEngine();
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), nonce, 0, nonce.Length);

            engine.Init(false, parameters);
            engine.ProcessBytes(data, 0, data.Length, dec, 0);

            return(dec);
        }
Beispiel #13
0
        internal static byte[] ChachaEncrypt(byte[] data, ref byte[] key, ref byte[] iv)
        {
            ChaChaEngine engine = new ChaChaEngine();

            key = key ?? RandomUtils.GetBytes(ChachaKeySize);
            iv  = iv ?? RandomUtils.GetBytes(ChachaKeySize / 2);
            engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
            byte[] result = new byte[iv.Length + data.Length];
            Array.Copy(iv, result, iv.Length);
            engine.ProcessBytes(data, 0, data.Length, result, iv.Length);
            return(result);
        }
Beispiel #14
0
        internal static void prg(byte[] r, int rOff, long rlen, byte[] key, int keyOff)
        {
            byte[] nonce = new byte[8];

            IStreamCipher cipher = new ChaChaEngine(12);

            cipher.Init(true, new KeyParameter(key, keyOff, 32));
            cipher.Init(true, new ParametersWithIV(null, nonce));

            cipher.ProcessBytes(r, rOff, (int)rlen, r, rOff);

            //crypto_stream_chacha12(r, rlen, nonce, key);
        }
Beispiel #15
0
        protected virtual KeyParameter InitRecordMac(ChaChaEngine cipher, bool forEncryption, long seqNo)
        {
            byte[] array = new byte[8];
            TlsUtilities.WriteUint64(seqNo, array, 0);
            cipher.Init(forEncryption, new ParametersWithIV(null, array));
            byte[] array2 = new byte[64];
            cipher.ProcessBytes(array2, 0, array2.Length, array2, 0);
            Array.Copy(array2, 0, array2, 32, 16);
            KeyParameter keyParameter = new KeyParameter(array2, 16, 32);

            Poly1305KeyGenerator.Clamp(keyParameter.GetKey());
            return(keyParameter);
        }
Beispiel #16
0
        public byte[] Encrypt(byte[] data)
        {
            ChaChaEngine chacha = new ChaChaEngine();

            byte[] iv = new byte[8];

            chacha.Init(true, new ParametersWithIV(_key, iv));

            byte[] output = new byte[data.Length + iv.Length];

            Array.Copy(iv, output, iv.Length);
            chacha.ProcessBytes(data, 0, data.Length, output, iv.Length);

            return(output);
        }
        protected virtual KeyParameter InitRecordMac(ChaChaEngine cipher, bool forEncryption, long seqNo)
        {
            byte[] nonce = new byte[8];
            TlsUtilities.WriteUint64(seqNo, nonce, 0);

            cipher.Init(forEncryption, new ParametersWithIV(null, nonce));

            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            // NOTE: The BC implementation puts 'r' after 'k'
            Array.Copy(firstBlock, 0, firstBlock, 32, 16);
            KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);

            Poly1305KeyGenerator.Clamp(macKey.GetKey());
            return(macKey);
        }
Beispiel #18
0
        /// <summary>
        /// Decloak the given buffer and return the valid Packet from it
        /// </summary>
        /// <param name="buffer">A cloaked packet buffer.</param>
        static public Packet Decloak(byte[] buffer)
        {
            if (buffer.Length < 8 || buffer [0] == 0)
            {
                return(Packet.DecodePacket(buffer));
            }

            byte[] nonce = buffer.Take(8).ToArray();
            var    parms = new ParametersWithIV(new KeyParameter(cloakKey), nonce);

            var chacha = new ChaChaEngine(20);

            chacha.Init(false, parms);
            byte[] outBuff = new byte[buffer.Length - 8];
            chacha.ProcessBytes(buffer, 8, buffer.Length - 8, outBuff, 0);

            return(Decloak(outBuff));
        }
        static byte[] DecryptStatic(byte[] src, out byte[] iv)
        {
            var key = new byte[] {
                0xD3, 0x61, 0x57, 0x17, 0xE2, 0x16, 0x3F, 0x70, 0xAC, 0x69, 0x51, 0xB2, 0x7D, 0x7A, 0x0B, 0x86,
                0xD8, 0xE9, 0x3E, 0x16, 0xEA, 0xBF, 0x63, 0x2F, 0xDF, 0xBC, 0xC0, 0x0A, 0x1D, 0x3D, 0x62, 0xD6
            };

            iv = new byte[8];
            Array.Copy(src, iv, 8);

            var cce = new ChaChaEngine();

            cce.Init(false, new ParametersWithIV(new KeyParameter(key), iv));

            var bsc = new BufferedStreamCipher(cce);

            return(bsc.ProcessBytes(src, 8, src.Length - 8));
        }
Beispiel #20
0
        private void reinitBug()
        {
            KeyParameter     key        = new KeyParameter(Hex.Decode("80000000000000000000000000000000"));
            ParametersWithIV parameters = new ParametersWithIV(key, Hex.Decode("0000000000000000"));

            IStreamCipher chacha = new ChaChaEngine();

            chacha.Init(true, parameters);

            try
            {
                chacha.Init(true, key);
                Fail("ChaCha should throw exception if no IV in Init");
            }
            catch (ArgumentException)
            {
            }
        }
Beispiel #21
0
        /********EXTERNAL OBJECT PUBLIC METHODS  - END ********/



        /// <summary>
        /// Buils the StreamCipher
        /// </summary>
        /// <param name="algorithm">SymmetrcStreamAlgorithm enum, algorithm name</param>
        /// <returns>IStreamCipher with the algorithm Stream Engine</returns>
        private IStreamCipher getCipherEngine(SymmetricStreamAlgorithm algorithm)
        {
            IStreamCipher engine = null;

            switch (algorithm)
            {
            case SymmetricStreamAlgorithm.RC4:
                engine = new RC4Engine();
                break;

            case SymmetricStreamAlgorithm.HC128:
                engine = new HC128Engine();
                break;

            case SymmetricStreamAlgorithm.HC256:
                engine = new HC256Engine();
                break;

            case SymmetricStreamAlgorithm.SALSA20:
                engine = new Salsa20Engine();
                break;

            case SymmetricStreamAlgorithm.CHACHA20:
                engine = new ChaChaEngine();
                break;

            case SymmetricStreamAlgorithm.XSALSA20:
                engine = new XSalsa20Engine();
                break;

            case SymmetricStreamAlgorithm.ISAAC:
                engine = new IsaacEngine();
                break;

            case SymmetricStreamAlgorithm.VMPC:
                engine = new VmpcEngine();
                break;

            default:
                this.GetError().setError("SS005", "Cipher " + algorithm + " not recognised.");
                break;
            }
            return(engine);
        }
Beispiel #22
0
        private void chachaTest2(
            ICipherParameters parameters,
            string v0,
            string v65472,
            string v65536)
        {
            IStreamCipher salsa = new ChaChaEngine();

            byte[] buf = new byte[64];

            salsa.Init(true, parameters);

            for (int i = 0; i != 1025; i++)
            {
                salsa.ProcessBytes(zeroes, 0, 64, buf, 0);
                switch (i)
                {
                case 0:
                    if (!AreEqual(buf, Hex.Decode(v0)))
                    {
                        mismatch("v0", v0, buf);
                    }
                    break;

                case 1023:
                    if (!AreEqual(buf, Hex.Decode(v65472)))
                    {
                        mismatch("v65472", v65472, buf);
                    }
                    break;

                case 1024:
                    if (!AreEqual(buf, Hex.Decode(v65536)))
                    {
                        mismatch("v65536", v65536, buf);
                    }
                    break;

                default:
                    // ignore
                    break;
                }
            }
        }
Beispiel #23
0
        // Encrypt data using Chacha engine
        public byte[] encryptWithChacha(byte[] input, byte[] key)
        {
            // Create a buffer that will contain the encrypted output and an 8 byte nonce
            byte[] outData = new byte[input.Length + 8];

            // Generate the 8 byte nonce
            byte[] nonce = new byte[8];

            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with a random value.
                rngCsp.GetBytes(nonce);
            }

            // Prevent leading 0 to avoid edge cases
            if (nonce[0] == 0)
            {
                nonce[0] = 1;
            }

            // Generate the Chacha engine
            var parms  = new ParametersWithIV(new KeyParameter(key), nonce);
            var chacha = new ChaChaEngine(chacha_rounds);

            try
            {
                chacha.Init(true, parms);
            }
            catch (Exception e)
            {
                Logging.error(string.Format("Error in chacha encryption. {0}", e.ToString()));
                return(null);
            }

            // Encrypt the input data while maintaing an 8 byte offset at the start
            chacha.ProcessBytes(input, 0, input.Length, outData, 8);

            // Copy the 8 byte nonce to the start of outData buffer
            Buffer.BlockCopy(nonce, 0, outData, 0, 8);

            // Return the encrypted data buffer
            return(outData);
        }
Beispiel #24
0
        // Decrypt data using Chacha engine
        public byte[] decryptWithChacha(byte[] input, byte[] key)
        {
            // Extract the nonce from the input
            byte[] nonce = input.Take(8).ToArray();

            // Generate the Chacha engine
            var parms  = new ParametersWithIV(new KeyParameter(key), nonce);
            var chacha = new ChaChaEngine(chacha_rounds);

            chacha.Init(false, parms);

            // Create a buffer that will contain the decrypted output
            byte[] outData = new byte[input.Length - 8];

            // Decrypt the input data
            chacha.ProcessBytes(input, 8, input.Length - 8, outData, 0);

            // Return the decrypted data buffer
            return(outData);
        }
        private KeyParameter InitRecordMAC(ChaChaEngine cipher)
        {
            byte[] zeroes = StringToByteArray(
                "00000000000000000000000000000000"
                + "00000000000000000000000000000000"
                + "00000000000000000000000000000000"
                + "00000000000000000000000000000000");

            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(zeroes, 0, firstBlock.Length, firstBlock, 0);

            Console.WriteLine("ChaCha OutBytes");
            Console.WriteLine(ByteArrayToString(firstBlock));

            // NOTE: The BC implementation puts 'r' after 'k'
            //Array.Copy(firstBlock, 0, firstBlock, 32, 16);
            //KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);
            //Poly1305KeyGenerator.clamp(macKey.getKey());

            // 8th January, 2018 21:05
            //
            // The above code is from the github HAP-Java implementation. The problem was that the clamp() operator
            // wasn't having any effect! I'm guessing it's because the getKey() returns a new instance each time.
            // To work around this, I create a buffer, clamp it and then create a KeyParameter with the new byte[]
            // How the f**k I spotted this I'll never know.
            //

            KeyParameter macKey = new KeyParameter(firstBlock, 0, 32);

            var key = macKey.GetKey();

            //Console.WriteLine(ByteArrayToString(key));

            Poly1305KeyGenerator.Clamp(key);

            //Console.WriteLine(ByteArrayToString(key));

            Poly1305KeyGenerator.CheckKey(key);

            return(new KeyParameter(key));
        }
Beispiel #26
0
        private static byte[] DoChaCha20(byte[] input, byte[] key, byte[] iv, bool encrypt)
        {
            if (key.Length != 16)
            {
                throw new Exception();
            }

            if (iv.Length != 8)
            {
                throw new Exception();
            }

            var buf = new byte[input.Length];

            var salsa = new ChaChaEngine(Rounds);
            ICipherParameters parameters = new ParametersWithIV(new KeyParameter(key), iv);

            salsa.Init(encrypt, parameters);
            salsa.ProcessBytes(input, 0, input.Length, buf, 0);
            return(buf);
        }
	public BcChaCha20OriginalCrypto(byte[] key, byte[] iv)
	{
		_engine = new ChaChaEngine();
		_engine.Init(default, new ParametersWithIV(new KeyParameter(key), iv));
Beispiel #28
0
        public static IBufferedCipher GetCipher(
            string algorithm)
        {
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            algorithm = Platform.ToUpperInvariant(algorithm);

            {
                string aliased = (string)algorithms[algorithm];

                if (aliased != null)
                {
                    algorithm = aliased;
                }
            }

            IBasicAgreement iesAgreement = null;

            if (algorithm == "IES")
            {
                iesAgreement = new DHBasicAgreement();
            }
            else if (algorithm == "ECIES")
            {
                iesAgreement = new ECDHBasicAgreement();
            }

            if (iesAgreement != null)
            {
                return(new BufferedIesCipher(
                           new IesEngine(
                               iesAgreement,
                               new Kdf2BytesGenerator(
                                   new Sha1Digest()),
                               new HMac(
                                   new Sha1Digest()))));
            }



            if (Platform.StartsWith(algorithm, "PBE"))
            {
                if (Platform.EndsWith(algorithm, "-CBC"))
                {
                    if (algorithm == "PBEWITHSHA1ANDDES-CBC")
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new DesEngine())));
                    }
                    else if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new RC2Engine())));
                    }
                    else if (Strings.IsOneOf(algorithm,
                                             "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new DesEdeEngine())));
                    }
                    else if (Strings.IsOneOf(algorithm,
                                             "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new RC2Engine())));
                    }
                }
                else if (Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL"))
                {
                    if (Strings.IsOneOf(algorithm,
                                        "PBEWITHSHAAND128BITAES-CBC-BC",
                                        "PBEWITHSHAAND192BITAES-CBC-BC",
                                        "PBEWITHSHAAND256BITAES-CBC-BC",
                                        "PBEWITHSHA256AND128BITAES-CBC-BC",
                                        "PBEWITHSHA256AND192BITAES-CBC-BC",
                                        "PBEWITHSHA256AND256BITAES-CBC-BC",
                                        "PBEWITHMD5AND128BITAES-CBC-OPENSSL",
                                        "PBEWITHMD5AND192BITAES-CBC-OPENSSL",
                                        "PBEWITHMD5AND256BITAES-CBC-OPENSSL"))
                    {
                        return(new PaddedBufferedBlockCipher(
                                   new CbcBlockCipher(new AesEngine())));
                    }
                }
            }



            string[] parts = algorithm.Split('/');

            IAeadCipher            aeadCipher      = null;
            IBlockCipher           blockCipher     = null;
            IAsymmetricBlockCipher asymBlockCipher = null;
            IStreamCipher          streamCipher    = null;

            string algorithmName = parts[0];

            {
                string aliased = (string)algorithms[algorithmName];

                if (aliased != null)
                {
                    algorithmName = aliased;
                }
            }

            CipherAlgorithm cipherAlgorithm;

            try
            {
                cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName);
            }
            catch (ArgumentException)
            {
                throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
            }

            switch (cipherAlgorithm)
            {
            case CipherAlgorithm.AES:
                blockCipher = new AesEngine();
                break;

            case CipherAlgorithm.ARC4:
                streamCipher = new RC4Engine();
                break;

            case CipherAlgorithm.BLOWFISH:
                blockCipher = new BlowfishEngine();
                break;

            case CipherAlgorithm.CAMELLIA:
                blockCipher = new CamelliaEngine();
                break;

            case CipherAlgorithm.CAST5:
                blockCipher = new Cast5Engine();
                break;

            case CipherAlgorithm.CAST6:
                blockCipher = new Cast6Engine();
                break;

            case CipherAlgorithm.CHACHA:
                streamCipher = new ChaChaEngine();
                break;

            case CipherAlgorithm.CHACHA20_POLY1305:
                aeadCipher = new ChaCha20Poly1305();
                break;

            case CipherAlgorithm.CHACHA7539:
                streamCipher = new ChaCha7539Engine();
                break;

            case CipherAlgorithm.DES:
                blockCipher = new DesEngine();
                break;

            case CipherAlgorithm.DESEDE:
                blockCipher = new DesEdeEngine();
                break;

            case CipherAlgorithm.ELGAMAL:
                asymBlockCipher = new ElGamalEngine();
                break;

            case CipherAlgorithm.GOST28147:
                blockCipher = new Gost28147Engine();
                break;

            case CipherAlgorithm.HC128:
                streamCipher = new HC128Engine();
                break;

            case CipherAlgorithm.HC256:
                streamCipher = new HC256Engine();
                break;

            case CipherAlgorithm.IDEA:
                blockCipher = new IdeaEngine();
                break;

            case CipherAlgorithm.NOEKEON:
                blockCipher = new NoekeonEngine();
                break;

            case CipherAlgorithm.PBEWITHSHAAND128BITRC4:
            case CipherAlgorithm.PBEWITHSHAAND40BITRC4:
                streamCipher = new RC4Engine();
                break;

            case CipherAlgorithm.RC2:
                blockCipher = new RC2Engine();
                break;

            case CipherAlgorithm.RC5:
                blockCipher = new RC532Engine();
                break;

            case CipherAlgorithm.RC5_64:
                blockCipher = new RC564Engine();
                break;

            case CipherAlgorithm.RC6:
                blockCipher = new RC6Engine();
                break;

            case CipherAlgorithm.RIJNDAEL:
                blockCipher = new RijndaelEngine();
                break;

            case CipherAlgorithm.RSA:
                asymBlockCipher = new RsaBlindedEngine();
                break;

            case CipherAlgorithm.SALSA20:
                streamCipher = new Salsa20Engine();
                break;

            case CipherAlgorithm.SEED:
                blockCipher = new SeedEngine();
                break;

            case CipherAlgorithm.SERPENT:
                blockCipher = new SerpentEngine();
                break;

            case CipherAlgorithm.SKIPJACK:
                blockCipher = new SkipjackEngine();
                break;

            case CipherAlgorithm.SM4:
                blockCipher = new SM4Engine();
                break;

            case CipherAlgorithm.TEA:
                blockCipher = new TeaEngine();
                break;

            case CipherAlgorithm.THREEFISH_256:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256);
                break;

            case CipherAlgorithm.THREEFISH_512:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512);
                break;

            case CipherAlgorithm.THREEFISH_1024:
                blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024);
                break;

            case CipherAlgorithm.TNEPRES:
                blockCipher = new TnepresEngine();
                break;

            case CipherAlgorithm.TWOFISH:
                blockCipher = new TwofishEngine();
                break;

            case CipherAlgorithm.VMPC:
                streamCipher = new VmpcEngine();
                break;

            case CipherAlgorithm.VMPC_KSA3:
                streamCipher = new VmpcKsa3Engine();
                break;

            case CipherAlgorithm.XTEA:
                blockCipher = new XteaEngine();
                break;

            default:
                throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
            }

            if (aeadCipher != null)
            {
                if (parts.Length > 1)
                {
                    throw new ArgumentException("Modes and paddings cannot be applied to AEAD ciphers");
                }

                return(new BufferedAeadCipher(aeadCipher));
            }

            if (streamCipher != null)
            {
                if (parts.Length > 1)
                {
                    throw new ArgumentException("Modes and paddings not used for stream ciphers");
                }

                return(new BufferedStreamCipher(streamCipher));
            }


            bool cts    = false;
            bool padded = true;
            IBlockCipherPadding padding         = null;
            IAeadBlockCipher    aeadBlockCipher = null;

            if (parts.Length > 2)
            {
                if (streamCipher != null)
                {
                    throw new ArgumentException("Paddings not used for stream ciphers");
                }

                string paddingName = parts[2];

                CipherPadding cipherPadding;
                if (paddingName == "")
                {
                    cipherPadding = CipherPadding.RAW;
                }
                else if (paddingName == "X9.23PADDING")
                {
                    cipherPadding = CipherPadding.X923PADDING;
                }
                else
                {
                    try
                    {
                        cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName);
                    }
                    catch (ArgumentException)
                    {
                        throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                    }
                }

                switch (cipherPadding)
                {
                case CipherPadding.NOPADDING:
                    padded = false;
                    break;

                case CipherPadding.RAW:
                    break;

                case CipherPadding.ISO10126PADDING:
                case CipherPadding.ISO10126D2PADDING:
                case CipherPadding.ISO10126_2PADDING:
                    padding = new ISO10126d2Padding();
                    break;

                case CipherPadding.ISO7816_4PADDING:
                case CipherPadding.ISO9797_1PADDING:
                    padding = new ISO7816d4Padding();
                    break;

                case CipherPadding.ISO9796_1:
                case CipherPadding.ISO9796_1PADDING:
                    asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
                    break;

                case CipherPadding.OAEP:
                case CipherPadding.OAEPPADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher);
                    break;

                case CipherPadding.OAEPWITHMD5ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest());
                    break;

                case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
                    break;

                case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
                    break;

                case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
                    break;

                case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
                    break;

                case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING:
                case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING:
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
                    break;

                case CipherPadding.PKCS1:
                case CipherPadding.PKCS1PADDING:
                    asymBlockCipher = new Pkcs1Encoding(asymBlockCipher);
                    break;

                case CipherPadding.PKCS5:
                case CipherPadding.PKCS5PADDING:
                case CipherPadding.PKCS7:
                case CipherPadding.PKCS7PADDING:
                    padding = new Pkcs7Padding();
                    break;

                case CipherPadding.TBCPADDING:
                    padding = new TbcPadding();
                    break;

                case CipherPadding.WITHCTS:
                    cts = true;
                    break;

                case CipherPadding.X923PADDING:
                    padding = new X923Padding();
                    break;

                case CipherPadding.ZEROBYTEPADDING:
                    padding = new ZeroBytePadding();
                    break;

                default:
                    throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                }
            }

            string mode = "";

            if (parts.Length > 1)
            {
                mode = parts[1];

                int    di       = GetDigitIndex(mode);
                string modeName = di >= 0 ? mode.Substring(0, di) : mode;

                try
                {
                    CipherMode cipherMode = modeName == ""
                        ? CipherMode.NONE
                        : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName);

                    switch (cipherMode)
                    {
                    case CipherMode.ECB:
                    case CipherMode.NONE:
                        break;

                    case CipherMode.CBC:
                        blockCipher = new CbcBlockCipher(blockCipher);
                        break;

                    case CipherMode.CCM:
                        aeadBlockCipher = new CcmBlockCipher(blockCipher);
                        break;

                    case CipherMode.CFB:
                    {
                        int bits = (di < 0)
                                ?       8 * blockCipher.GetBlockSize()
                                :       int.Parse(mode.Substring(di));

                        blockCipher = new CfbBlockCipher(blockCipher, bits);
                        break;
                    }

                    case CipherMode.CTR:
                        blockCipher = new SicBlockCipher(blockCipher);
                        break;

                    case CipherMode.CTS:
                        cts         = true;
                        blockCipher = new CbcBlockCipher(blockCipher);
                        break;

                    case CipherMode.EAX:
                        aeadBlockCipher = new EaxBlockCipher(blockCipher);
                        break;

                    case CipherMode.GCM:
                        aeadBlockCipher = new GcmBlockCipher(blockCipher);
                        break;

                    case CipherMode.GOFB:
                        blockCipher = new GOfbBlockCipher(blockCipher);
                        break;

                    case CipherMode.OCB:
                        aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm));
                        break;

                    case CipherMode.OFB:
                    {
                        int bits = (di < 0)
                                ?       8 * blockCipher.GetBlockSize()
                                :       int.Parse(mode.Substring(di));

                        blockCipher = new OfbBlockCipher(blockCipher, bits);
                        break;
                    }

                    case CipherMode.OPENPGPCFB:
                        blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
                        break;

                    case CipherMode.SIC:
                        if (blockCipher.GetBlockSize() < 16)
                        {
                            throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
                        }
                        blockCipher = new SicBlockCipher(blockCipher);
                        break;

                    default:
                        throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                    }
                }
                catch (ArgumentException)
                {
                    throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                }
            }

            if (aeadBlockCipher != null)
            {
                if (cts)
                {
                    throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
                }
                if (padded && parts.Length > 2 && parts[2] != "")
                {
                    throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
                }

                return(new BufferedAeadBlockCipher(aeadBlockCipher));
            }

            if (blockCipher != null)
            {
                if (cts)
                {
                    return(new CtsBlockCipher(blockCipher));
                }

                if (padding != null)
                {
                    return(new PaddedBufferedBlockCipher(blockCipher, padding));
                }

                if (!padded || blockCipher.IsPartialBlockOkay)
                {
                    return(new BufferedBlockCipher(blockCipher));
                }

                return(new PaddedBufferedBlockCipher(blockCipher));
            }

            if (asymBlockCipher != null)
            {
                return(new BufferedAsymmetricBlockCipher(asymBlockCipher));
            }

            throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
        }