Пример #1
0
        public static void Main(string[] args)
        {
            string cube3File  = null;
            string scriptFile = null;

            if (args.Length > 0)
            {
                cube3File = args[0];
                if (args.Length > 1)
                {
                    scriptFile = args[1];
                }
            }

            if (cube3File == null)
            {
                System.Console.WriteLine("usage: c3sg <cube3File> [<scriptFile>]");
                System.Console.WriteLine("");
                System.Console.WriteLine("c3sg reads cube3File and generates a script file.  Will generate file");
                System.Console.WriteLine("in specified scriptFile or in a file with the same name as the Cube3 File,");
                System.Console.WriteLine("but with the extension CUBESCR");
                System.Console.WriteLine("");
                Environment.Exit(0);
            }

            if (scriptFile == null)
            {
                scriptFile = Path.GetFileNameWithoutExtension(cube3File) + ".CUBESCR";
            }

            engine = new BlowfishEngine(true);
            generateScriptFromCube3File(cube3File, scriptFile);
        }
Пример #2
0
        public void saveKeysToFiles()
        {
            //save keys of a new user to files
            using (FileStream fs = File.Create(MainWindow.publicKeysPath + "\\" + Email + ".txt"))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(publicKey);
                fs.Write(info, 0, info.Length);
            }
            using (FileStream fs = File.Create(MainWindow.privateKeysPath + "\\" + Email + ".txt"))
            {
                Byte[] privateKeyBytes = new UTF8Encoding(true).GetBytes(privateKey);
                string key             = computeSha256Hash(password); //hashed password

                BlowfishEngine            engine = new BlowfishEngine();
                PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine); //ECB
                KeyParameter keyBytes            = new KeyParameter(Encoding.UTF8.GetBytes(key));

                cipher.Init(true, keyBytes);
                encPrivateKey = new byte[cipher.GetOutputSize(privateKeyBytes.Length)];
                int len1 = cipher.ProcessBytes(privateKeyBytes, 0, privateKeyBytes.Length, encPrivateKey, 0); //private key encrypted with hashed password
                cipher.DoFinal(encPrivateKey, len1);

                fs.Write(encPrivateKey, 0, encPrivateKey.Length);
            }
        }
Пример #3
0
 /**
  * @param blowfishKey
  */
 public NewCrypt(byte[] blowfishKey)
 {
     _crypt = new BlowfishEngine();
     _crypt.init(true, blowfishKey);
     _decrypt = new BlowfishEngine();
     _decrypt.init(false, blowfishKey);
 }
Пример #4
0
        public void TestFunction()
        {
            string resultText = Perform().ToString();

            BlowfishEngine blowfish = new BlowfishEngine();

            // key range check
            try
            {
                blowfish.Init(true, new KeyParameter(new byte[1]));
                Fail("no exception");
            }
            catch (ArgumentException e)
            {
                Assert.AreEqual("key length must be in range 32 to 448 bits", e.Message);
            }

            try
            {
                blowfish.Init(true, new KeyParameter(new byte[59]));
                Fail("no exception");
            }
            catch (ArgumentException e)
            {
                Assert.AreEqual("key length must be in range 32 to 448 bits", e.Message);
            }

            Assert.AreEqual(Name + ": Okay", resultText);
        }
Пример #5
0
        /// <summary>
        /// After being initialized with a key, the schedule (p-array) and s-boxes needs some
        /// work from the Blowfish engine to finish setting up.
        /// </summary>
        void Setup()
        {
            // The setup process starts with the all zero string.
            UInt64 bitScape = 0;

            // To set up the schedule (p-arrays),
            for (int i = 0; i < 9; i++)
            {
                bitScape = BlowfishEngine.Encrypt(ByteOperations.Swap(bitScape), this);
                Schedule.Set(i * 2, ByteOperations.Left(bitScape));
                Schedule.Set(i * 2 + 1, ByteOperations.Right(bitScape));
                bitScape = ByteOperations.Swap(bitScape);
            }

            // To finish the s-boxes
            for (int i = 0; i < 1024;)
            {
                bitScape = BlowfishEngine.Encrypt(ByteOperations.Swap(bitScape), this);

                sbox[i / 256, i % 256] = ByteOperations.Left(bitScape);
                i++;
                sbox[i / 256, i % 256] = ByteOperations.Right(bitScape);
                i++;

                bitScape = ByteOperations.Swap(bitScape);
            }
        }
Пример #6
0
        public static void Main(string[] args)
        {
            string cube3File = null;
            string bfbFile   = null;

            if (args.Length > 0)
            {
                bfbFile = args[0];
                if (args.Length > 1)
                {
                    cube3File = args[1];
                }
            }

            if (bfbFile == null)
            {
                System.Console.WriteLine("usage: cube3Encoder <bfbFile> [<Cube3File>]");
                System.Console.WriteLine("");
                System.Console.WriteLine("cube3Encoder reads bfbFile and encodes into Cube3File.   Will generate");
                System.Console.WriteLine("into specified Cube3File or a file with the same name as the BFB File,");
                System.Console.WriteLine("but with the extension Cube3");
                System.Console.WriteLine("");
                Environment.Exit(0);
            }

            if (cube3File == null)
            {
                cube3File = Path.GetFileNameWithoutExtension(bfbFile) + ".Cube3";
            }

            engine = new BlowfishEngine(true);
            generateCube3FromBFBFile(bfbFile, cube3File);
        }
Пример #7
0
 public NewCrypt(string key)
 {
     byte[] blowfishKey = Encoding.UTF8.GetBytes(key);
     _crypt = new BlowfishEngine();
     _crypt.init(true, blowfishKey);
     _decrypt = new BlowfishEngine();
     _decrypt.init(false, blowfishKey);
 }
Пример #8
0
 public CryptoEngine(Window window, FileManager fileManager)
 {
     this.window      = window;
     this.fileManager = fileManager;
     engine           = new BlowfishEngine();
     iv             = null;
     subBlockLength = 1;
 }
Пример #9
0
        public static void Main(string[] args)
        {
            int cube3FileIndex = 0;
            int bfbFileIndex   = 1;

            bool   xmlMode   = false;
            string cube3File = null;
            string bfbFile   = null;

            if (args.Length > 0)
            {
                if (args[0].StartsWith("-") || args[0].StartsWith("/"))
                {
                    cube3FileIndex++;
                    bfbFileIndex++;

                    if (args[0].ToUpper().Equals("-XML"))
                    {
                        xmlMode = true;
                    }
                    else
                    {
                        System.Console.WriteLine($"Invalid parameter {args[0]}!");
                        System.Console.WriteLine("");
                        displayHelp();
                        Environment.Exit(-1);
                    }
                }
                cube3File = args[cube3FileIndex];
                if (args.Length > bfbFileIndex)
                {
                    bfbFile = args[bfbFileIndex];
                }
            }

            if (cube3File == null)
            {
                displayHelp();
                Environment.Exit(0);
            }

            if (bfbFile == null)
            {
                if (!xmlMode)
                {
                    bfbFile = Path.GetFileNameWithoutExtension(cube3File) + ".BFB";
                }
                else
                {
                    bfbFile = Path.GetFileNameWithoutExtension(cube3File) + ".XML";
                }
            }

            engine = new BlowfishEngine();
            engine.UseLittleEndian = true;
            generateBFBFromCube3File(cube3File, bfbFile, xmlMode);
        }
Пример #10
0
        const string KEY = "wHcnqpHNN"; // "STINGMIMI";

        public static string Decode4odToken(string token)
        {
            byte[]         encryptedBytes = Convert.FromBase64String(token);
            BlowfishEngine bf             = new BlowfishEngine();

            bf.Init(false, new KeyParameter(Encoding.ASCII.GetBytes(KEY)));
            byte[] decryptedBytes = decrypt(encryptedBytes, bf);
            return(Encoding.ASCII.GetString(decryptedBytes));
        }
Пример #11
0
        static void Main(string[] args)
        {
            BlowfishEngine engine = new BlowfishEngine();
            RestClient     client = new RestClient("http://spectator.na.lol.riotgames.com:80/observer-mode/rest/");

            JSON.Deserialize <Game[]>(
                JSON.DeserializeDynamic(
                    client.Execute(new RestRequest("featured", Method.GET)).Content
                    ).gameList
                );
        }
Пример #12
0
        private string decryptPath(string path)
        {
            byte[]         value = StringToBytes(path);
            BlowfishEngine bf    = new BlowfishEngine();

            byte[] key1 = new byte[7] {
                107, 108, 117, 99, 122, 121, 107
            };
            bf.Init(true, new KeyParameter(key1));
            decrypt(value, bf);
            return(Encoding.ASCII.GetString(value));
        }
Пример #13
0
        //private
        private static byte[] encryptDecrypt(byte[] input, byte[] key, byte[] iv, BlockMode mode, BlockPadding padding, bool encrypt)
        {
            BlowfishEngine      engine = new BlowfishEngine();
            IBlockCipher        cipherMode;
            BufferedBlockCipher cipher;
            KeyParameter        keyP      = new KeyParameter(key);
            ParametersWithIV    keyParams = new ParametersWithIV(keyP, iv);

            if (mode == BlockMode.CBC)
            {
                cipherMode = new CbcBlockCipher(engine);
            }
            else if (mode == BlockMode.CFB)
            {
                cipherMode = new CfbBlockCipher(engine, iv.Length);
            }
            else if (mode == BlockMode.OFB)
            {
                cipherMode = new OfbBlockCipher(engine, iv.Length);
            }
            else
            {
                throw new Exception("mode must be a valid BlockMode.");
            }

            if (padding == BlockPadding.PKCS7Padding)
            {
                cipher = new PaddedBufferedBlockCipher(cipherMode, new Pkcs7Padding());
            }
            else if (padding == BlockPadding.ZeroBytePadding)
            {
                cipher = new PaddedBufferedBlockCipher(cipherMode, new ZeroBytePadding());
            }
            else if (padding == BlockPadding.NoPadding)
            {
                cipher = new BufferedBlockCipher(cipherMode);
            }
            else
            {
                throw new Exception("padding must be a valid BlockPadding.");
            }

            cipher.Init(encrypt, keyParams);
            byte[] output = new byte[cipher.GetOutputSize(input.Length)];
            int    length = cipher.ProcessBytes(input, output, 0);

            cipher.DoFinal(output, length);

            return(output);
        }
Пример #14
0
        public void decryptPrivateKey(string keyString)
        {
            //decrypt private key with key = user password hashed with SHA-256
            BlowfishEngine            engine = new BlowfishEngine();
            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
            StringBuilder             result = new StringBuilder();

            cipher.Init(false, new KeyParameter(Encoding.UTF8.GetBytes(keyString)));
            byte[] out2 = new byte[cipher.GetOutputSize(encPrivateKey.Length)];
            int    len2 = cipher.ProcessBytes(encPrivateKey, 0, encPrivateKey.Length, out2, 0);

            cipher.DoFinal(out2, len2);

            this.privateKey = Encoding.UTF8.GetString(out2);
        }
        public string Encrypt(string plainText, string key)
        {
            var engine   = new BlowfishEngine();
            var cipher   = new PaddedBufferedBlockCipher(engine);
            var keyBytes = new KeyParameter(Encoding.UTF8.GetBytes(key));

            cipher.Init(true, keyBytes);

            var plainBytes = Encoding.UTF8.GetBytes(plainText);
            var result     = new byte[cipher.GetOutputSize(plainBytes.Length)];
            var length     = cipher.ProcessBytes(plainBytes, 0, plainBytes.Length, result, 0);

            cipher.DoFinal(result, length);

            var base64 = Convert.ToBase64String(result);

            return(base64);
        }
Пример #16
0
        static byte[] decrypt(byte[] byteArray, BlowfishEngine bf)
        {
            int         blockSize = 8;
            List <byte> decrypted = new List <byte>();

            for (int i = 0; i < byteArray.Length; i = i + blockSize)
            {
                byte[] blockBytes = new byte[blockSize];
                byte[] outBytes   = new byte[blockSize];
                for (int j = 0; j < blockSize; j++)
                {
                    blockBytes[j] = byteArray[i + j];
                }
                bf.ProcessBlock(blockBytes, 0, outBytes, 0);
                decrypted.AddRange(outBytes);
            }
            unpad(decrypted);
            return(decrypted.ToArray());
        }
Пример #17
0
        /// <summary>
        /// Encrypted the data.
        /// </summary>
        /// <param name="data">The data to encrypted.</param>
        /// <param name="passphrase">The passphrase key used to mask the data.</param>
        /// <returns>The encrypted data.</returns>
        public byte[] Encrypt(byte[] data, string passphrase)
        {
            // Create the key parameters.
            byte[] key = Encoding.Default.GetBytes(passphrase);
            Key.Crypto.Parameters.KeyParameter keyParameter = new KeyParameter(key);

            // Initialise the cryptography engine.
            Key.Crypto.Engines.BlowfishEngine blowfish = new BlowfishEngine();
            blowfish.Init(true, keyParameter);

            int dataLength   = data.Length;
            int blockSize    = blowfish.GetBlockSize();
            int modBlockSize = dataLength % blockSize;
            int blockCount   = dataLength / blockSize;

            // If there is a remained then add en extra block count.
            if ((modBlockSize) > 0)
            {
                // Add one extra block.
                blockCount++;
            }

            // Encrypted data store.
            byte[] encryptedData = new byte[blockCount * blockSize];
            byte[] decryptedData = new byte[blockCount * blockSize];

            // Copy the decrypted data.
            for (int j = 0; j < dataLength; j++)
            {
                // Assign the data.
                decryptedData[j] = data[j];
            }

            // For each block size in the the data.
            for (int i = 0; i < blockCount; i++)
            {
                // Encrypt the block.
                blowfish.ProcessBlock(decryptedData, (i * blockSize), encryptedData, (i * blockSize));
            }

            // Return the encrypted data.
            return(encryptedData);
        }
Пример #18
0
        public static ArrayLease <byte> DecryptBytes(ArraySegment <byte> ciphertext, ArraySegment <byte> key, out int count)
        {
            // Blowfish processes things in blocks of 8, so
            // it doesn't make sense to have a non-multiple
            // of 8 length ciphertext (TODO: right?)
            if ((ciphertext.Count & 7) != 0) // ciphertext.Count % 8 != 0
            {
                // TODO: Have a Strings.resx file for this
                // Does project.json support that? / What benefits will that yield?
                throw new ArgumentException(
                          message: "The length of the ciphertext needs to be divisible by 8.",
                          paramName: nameof(ciphertext));
            }

            // Since there's guaranteed to be no leftover,
            // the count is just ciphertext.Count
            count = ciphertext.Count;

            var engine       = new BlowfishEngine();
            var keyParameter = new KeyParameter(key.Array, key.Offset, key.Count);

            engine.Init(forEncryption: false, parameters: keyParameter);

            var lease = ArrayPool <byte> .Shared.Lease(count);

            try
            {
                var encryptBuffer = ciphertext.Array;
                var decryptBuffer = lease.Array;

                for (int i = 0; i < count; i += 8)
                {
                    engine.ProcessBlock(encryptBuffer, ciphertext.Offset + i, decryptBuffer, i);
                }
            }
            catch
            {
                lease.Dispose();
                throw;
            }

            return(lease);
        }
        public byte[] BlowfishEncrypt(byte[] contentBytes, string key)
        {
            try
            {
                //create blowfish engine
                BlowfishEngine engine = new BlowfishEngine();
                //create block cipher based on user choice
                PaddedBufferedBlockCipher cipher = null;
                switch (encryptTypes[encryptTypeIndex])
                {
                case "ECB":
                    cipher = new PaddedBufferedBlockCipher(engine);
                    break;

                case "CBC":
                    cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine));
                    break;

                case "CFB":
                    cipher = new PaddedBufferedBlockCipher(new CfbBlockCipher(engine, blockSize));
                    break;

                case "OFB":
                    cipher = new PaddedBufferedBlockCipher(new OfbBlockCipher(engine, blockSize));
                    break;
                }
                //create key
                KeyParameter keyBytes = new KeyParameter(Encoding.GetBytes(key));
                cipher.Init(true, keyBytes);

                //create byte array for encrypted data
                byte[] outB = new byte[cipher.GetOutputSize(contentBytes.Length)];
                int    len1 = cipher.ProcessBytes(contentBytes, 0, contentBytes.Length, outB, 0);
                cipher.DoFinal(outB, len1);

                return(outB);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #20
0
        public string EncryptWithBouncyCastle(
            string token,
            string encryptionKey
            )
        {
            IBlockCipher blowFishCipher = new BlowfishEngine();

            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blowFishCipher);

            cipher.Init(true, new KeyParameter(Base64.Decode(encryptionKey)));

            var encoder = new ASCIIEncoding();

            byte[] tokenBytes = encoder.GetBytes(token);

            byte[] encryptedTokenBytes = cipher.DoFinal(tokenBytes);
            var    encryptedToken      = Convert.ToBase64String(encryptedTokenBytes);

            return(encryptedToken);
        }
Пример #21
0
        private static byte[] DecryptChunks(byte[] downloadBytes, long streamLength, byte[] keyBytes)
        {
            var decryptedBytes = new byte[streamLength];
            var chunkSize      = 2048;
            var progress       = 0;

            while (progress < streamLength)
            {
                if (streamLength - progress < 2048)
                {
                    chunkSize = (int)streamLength - progress;
                }

                var encryptedChunk = new byte[chunkSize];

                Buffer.BlockCopy(downloadBytes, progress, encryptedChunk, 0, chunkSize);

                // this will only decrypt every third chunk and if it's not at the end
                if (progress % (chunkSize * 3) == 0 && chunkSize == 2048)
                {
                    var blowfishEngine = new BlowfishEngine();
                    var cipher         = new PaddedBufferedBlockCipher(new CbcBlockCipher(blowfishEngine), new ZeroBytePadding());
                    var keyParameter   = new KeyParameter(keyBytes);
                    var parameters     = new ParametersWithIV(keyParameter, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
                    cipher.Init(false, parameters);

                    var output = new byte[cipher.GetOutputSize(encryptedChunk.Length)];
                    int len    = cipher.ProcessBytes(encryptedChunk, 0, encryptedChunk.Length, output, 0);
                    cipher.DoFinal(output, len);
                    Buffer.BlockCopy(output, 0, encryptedChunk, 0, output.Length);
                }

                Buffer.BlockCopy(encryptedChunk, 0, decryptedBytes, progress, encryptedChunk.Length);

                progress += chunkSize;
            }

            return(decryptedBytes);
        }
Пример #22
0
        private void decrypt(byte[] value, BlowfishEngine bf)
        {
            int blockSize = bf.GetBlockSize();

            byte[] vector = new byte[blockSize];
            for (int i = 0; i < blockSize; i++)
            {
                vector[i] = 0;
            }
            for (int i = 0; i < value.Length; i += blockSize)
            {
                byte[] tmp = new byte[blockSize];
                bf.ProcessBlock(vector, 0, tmp, 0);
                int chunk = Math.Min(blockSize, value.Length - i);
                for (int j = 0; j < chunk; j++)
                {
                    vector[j]      = value[i + j];
                    value[(i + j)] = (byte)(value[(i + j)] ^ tmp[j]);
                }
                ;
            }
            ;
        }
Пример #23
0
        static private string BlowfishEncrypt(string strValue, string key)
        {
            try
            {
                Encoding                  encoding = Encoding.UTF8;
                BlowfishEngine            engine   = new BlowfishEngine();
                PaddedBufferedBlockCipher cipher   = new PaddedBufferedBlockCipher(engine);

                cipher.Init(true, new KeyParameter(encoding.GetBytes(key)));

                byte[] inn  = encoding.GetBytes(strValue);
                byte[] outt = new byte[cipher.GetOutputSize(inn.Length)];

                int len1 = cipher.ProcessBytes(inn, 0, inn.Length, outt, 0);

                cipher.DoFinal(outt, len1);

                return(BitConverter.ToString(outt).Replace("-", ""));
            }
            catch (Exception)
            {
                return("");
            }
        }
        public byte[] BlowfishDecrypt(byte[] contentBytes, string keyString, string cipherMode)
        {
            //create blowfish engine
            BlowfishEngine engine = new BlowfishEngine();
            //create block cipher based on user choice
            PaddedBufferedBlockCipher cipher = null;

            switch (cipherMode)
            {
            case "ECB":
                cipher = new PaddedBufferedBlockCipher(engine);
                break;

            case "CBC":
                cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine));
                break;

            case "CFB":
                cipher = new PaddedBufferedBlockCipher(new CfbBlockCipher(engine, blockSize));
                break;

            case "OFB":
                cipher = new PaddedBufferedBlockCipher(new OfbBlockCipher(engine, blockSize));
                break;
            }
            StringBuilder result = new StringBuilder();

            cipher.Init(false, new KeyParameter(Encoding.GetBytes(keyString)));

            byte[] out2 = new byte[cipher.GetOutputSize(contentBytes.Length)];
            int    len2 = cipher.ProcessBytes(contentBytes, 0, contentBytes.Length, out2, 0);

            cipher.DoFinal(out2, len2);

            return(out2);
        }
Пример #25
0
        private static byte[] ProcessData(byte[] data, byte[] key, bool forEncryption)
        {
            byte[] input = data;

            bool paddingRequired = data.Length % BlockSize > 0;

            if (paddingRequired)
            {
                input = new byte[data.Length + BlockSize - data.Length % BlockSize];
                Buffer.BlockCopy(data, 0, input, 0, data.Length);
            }

            byte[] output = new byte[input.Length];

            BlowfishEngine engine = new BlowfishEngine();

            engine.Init(forEncryption, key);

            int offset = 0;

            while (offset < input.Length)
            {
                engine.ProcessBlock(input, offset, output, offset);

                offset += BlockSize;
            }

            if (paddingRequired)
            {
                byte[] unpaddedOutput = new byte[data.Length];
                Buffer.BlockCopy(output, 0, unpaddedOutput, 0, unpaddedOutput.Length);
                return(unpaddedOutput);
            }

            return(output);
        }
Пример #26
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 AesFastEngine())));
                    }
                }
            }



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

            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 AesFastEngine();
                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.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.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 (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.");
        }
        /// <summary>
        /// Build the engine
        /// </summary>
        /// <param name="algorithm">SymmetricBlockAlgorithm enum, algorithm name</param>
        /// <returns>IBlockCipher with the algorithm Engine</returns>
        internal IBlockCipher getCipherEngine(SymmetricBlockAlgorithm algorithm)
        {
            IBlockCipher engine = null;

            switch (algorithm)
            {
            case SymmetricBlockAlgorithm.AES:
                engine = new AesEngine();
                break;

            case SymmetricBlockAlgorithm.BLOWFISH:
                engine = new BlowfishEngine();
                break;

            case SymmetricBlockAlgorithm.CAMELLIA:
                engine = new CamelliaEngine();
                break;

            case SymmetricBlockAlgorithm.CAST5:
                engine = new Cast5Engine();
                break;

            case SymmetricBlockAlgorithm.CAST6:
                engine = new Cast6Engine();
                break;

            case SymmetricBlockAlgorithm.DES:
                engine = new DesEngine();
                break;

            case SymmetricBlockAlgorithm.TRIPLEDES:
                engine = new DesEdeEngine();
                break;

            case SymmetricBlockAlgorithm.DSTU7624_128:
                engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_128, this.error));
                break;

            case SymmetricBlockAlgorithm.DSTU7624_256:
                engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_256, this.error));
                break;

            case SymmetricBlockAlgorithm.DSTU7624_512:
                engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_512, this.error));
                break;

            case SymmetricBlockAlgorithm.GOST28147:
                engine = new Gost28147Engine();
                break;

            case SymmetricBlockAlgorithm.NOEKEON:
                engine = new NoekeonEngine();
                break;

            case SymmetricBlockAlgorithm.RC2:
                engine = new RC2Engine();
                break;

            case SymmetricBlockAlgorithm.RC532:
                engine = new RC532Engine();
                break;

            case SymmetricBlockAlgorithm.RC564:
                engine = new RC564Engine();
                break;

            case SymmetricBlockAlgorithm.RC6:
                engine = new RC6Engine();
                break;

            case SymmetricBlockAlgorithm.RIJNDAEL_128:
                engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_128, this.error));
                break;

            case SymmetricBlockAlgorithm.RIJNDAEL_160:
                engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_160, this.error));
                break;

            case SymmetricBlockAlgorithm.RIJNDAEL_192:
                engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_192, this.error));
                break;

            case SymmetricBlockAlgorithm.RIJNDAEL_224:
                engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_224, this.error));
                break;

            case SymmetricBlockAlgorithm.RIJNDAEL_256:
                engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_256, this.error));
                break;

            case SymmetricBlockAlgorithm.SEED:
                engine = new SeedEngine();
                break;

            case SymmetricBlockAlgorithm.SERPENT:
                engine = new SerpentEngine();
                break;

            case SymmetricBlockAlgorithm.SKIPJACK:
                engine = new SkipjackEngine();
                break;

            case SymmetricBlockAlgorithm.SM4:
                engine = new SM4Engine();
                break;

            case SymmetricBlockAlgorithm.TEA:
                engine = new TeaEngine();
                break;

            case SymmetricBlockAlgorithm.THREEFISH_256:
                engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_256, this.error));
                break;

            case SymmetricBlockAlgorithm.THREEFISH_512:
                engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_512, this.error));
                break;

            case SymmetricBlockAlgorithm.THREEFISH_1024:
                engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_1024, this.error));
                break;

            case SymmetricBlockAlgorithm.TWOFISH:
                engine = new TwofishEngine();
                break;

            case SymmetricBlockAlgorithm.XTEA:
                engine = new XteaEngine();
                break;

            default:
                this.error.setError("SB020", "Cipher " + algorithm + " not recognised.");
                break;
            }
            return(engine);
        }
        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 (algorithm.StartsWith("PBE"))
            {
                if (algorithm.EndsWith("-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 (algorithm.EndsWith("-BC") || algorithm.EndsWith("-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 AesFastEngine()));
                    }
                }
            }

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

            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 AesFastEngine();
                    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.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.TEA:
                    blockCipher = new TeaEngine();
                    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 (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.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.");
        }
Пример #29
0
        public static IBufferedCipher GetCipher(string algorithm)
        {
            //IL_0008: Unknown result type (might be due to invalid IL or missing references)
            //IL_0469: Unknown result type (might be due to invalid IL or missing references)
            //IL_0495: Unknown result type (might be due to invalid IL or missing references)
            //IL_07f1: Unknown result type (might be due to invalid IL or missing references)
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }
            algorithm = Platform.ToUpperInvariant(algorithm);
            string text = (string)algorithms.get_Item((object)algorithm);

            if (text != null)
            {
                algorithm = text;
            }
            IBasicAgreement basicAgreement = null;

            if (algorithm == "IES")
            {
                basicAgreement = new DHBasicAgreement();
            }
            else if (algorithm == "ECIES")
            {
                basicAgreement = new ECDHBasicAgreement();
            }
            if (basicAgreement != null)
            {
                return(new BufferedIesCipher(new IesEngine(basicAgreement, 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())));
                    }
                    if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
                    {
                        return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new RC2Engine())));
                    }
                    if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
                    {
                        return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine())));
                    }
                    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")) && 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 AesFastEngine())));
                }
            }
            string[] array = algorithm.Split(new char[1] {
                '/'
            });
            IBlockCipher           blockCipher           = null;
            IAsymmetricBlockCipher asymmetricBlockCipher = null;
            IStreamCipher          streamCipher          = null;
            string text2 = array[0];
            string text3 = (string)algorithms.get_Item((object)text2);

            if (text3 != null)
            {
                text2 = text3;
            }
            CipherAlgorithm cipherAlgorithm;

            try
            {
                cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), text2);
            }
            catch (ArgumentException)
            {
                throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
            }
            switch (cipherAlgorithm)
            {
            case CipherAlgorithm.AES:
                blockCipher = new AesFastEngine();
                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.DES:
                blockCipher = new DesEngine();
                break;

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

            case CipherAlgorithm.ELGAMAL:
                asymmetricBlockCipher = 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:
                asymmetricBlockCipher = 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.TEA:
                blockCipher = new TeaEngine();
                break;

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

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

            case CipherAlgorithm.THREEFISH_1024:
                blockCipher = new ThreefishEngine(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 (streamCipher != null)
            {
                if (array.Length > 1)
                {
                    throw new ArgumentException("Modes and paddings not used for stream ciphers");
                }
                return(new BufferedStreamCipher(streamCipher));
            }
            bool flag  = false;
            bool flag2 = true;
            IBlockCipherPadding blockCipherPadding = null;
            IAeadBlockCipher    aeadBlockCipher    = null;

            if (array.Length > 2)
            {
                if (streamCipher != null)
                {
                    throw new ArgumentException("Paddings not used for stream ciphers");
                }
                string        text4 = array[2];
                CipherPadding cipherPadding;
                if (text4 == "")
                {
                    cipherPadding = CipherPadding.RAW;
                }
                else if (text4 == "X9.23PADDING")
                {
                    cipherPadding = CipherPadding.X923PADDING;
                }
                else
                {
                    try
                    {
                        cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), text4);
                    }
                    catch (ArgumentException)
                    {
                        throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                    }
                }
                switch (cipherPadding)
                {
                case CipherPadding.NOPADDING:
                    flag2 = false;
                    break;

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

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

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

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

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

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

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

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

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

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

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

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

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

                case CipherPadding.WITHCTS:
                    flag = true;
                    break;

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

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

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

                case CipherPadding.RAW:
                    break;
                }
            }
            string text5 = "";

            if (array.Length > 1)
            {
                text5 = array[1];
                int    digitIndex = GetDigitIndex(text5);
                string text6      = ((digitIndex >= 0) ? text5.Substring(0, digitIndex) : text5);
                try
                {
                    switch ((text6 == "") ? CipherMode.NONE : ((CipherMode)Enums.GetEnumValue(typeof(CipherMode), text6)))
                    {
                    case CipherMode.CBC:
                        blockCipher = new CbcBlockCipher(blockCipher);
                        break;

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

                    case CipherMode.CFB:
                    {
                        int bitBlockSize = ((digitIndex < 0) ? (8 * blockCipher.GetBlockSize()) : int.Parse(text5.Substring(digitIndex)));
                        blockCipher = new CfbBlockCipher(blockCipher, bitBlockSize);
                        break;
                    }

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

                    case CipherMode.CTS:
                        flag        = 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 blockSize = ((digitIndex < 0) ? (8 * blockCipher.GetBlockSize()) : int.Parse(text5.Substring(digitIndex)));
                        blockCipher = new OfbBlockCipher(blockCipher, blockSize);
                        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.");

                    case CipherMode.ECB:
                    case CipherMode.NONE:
                        break;
                    }
                }
                catch (ArgumentException)
                {
                    throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
                }
            }
            if (aeadBlockCipher != null)
            {
                if (flag)
                {
                    throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
                }
                if (flag2 && array.Length > 2 && array[2] != "")
                {
                    throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
                }
                return(new BufferedAeadBlockCipher(aeadBlockCipher));
            }
            if (blockCipher != null)
            {
                if (flag)
                {
                    return(new CtsBlockCipher(blockCipher));
                }
                if (blockCipherPadding != null)
                {
                    return(new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding));
                }
                if (!flag2 || blockCipher.IsPartialBlockOkay)
                {
                    return(new BufferedBlockCipher(blockCipher));
                }
                return(new PaddedBufferedBlockCipher(blockCipher));
            }
            if (asymmetricBlockCipher != null)
            {
                return(new BufferedAsymmetricBlockCipher(asymmetricBlockCipher));
            }
            throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
        }
        public static IBufferedCipher GetCipher(
            string algorithm)
        {
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            algorithm = algorithm.ToUpper(CultureInfo.InvariantCulture);

            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 (algorithm.StartsWith("PBE"))
            {
                switch (algorithm)
                {
                case "PBEWITHSHAAND2-KEYTRIPLEDES-CBC":
                case "PBEWITHSHAAND3-KEYTRIPLEDES-CBC":
                    return(new PaddedBufferedBlockCipher(
                               new CbcBlockCipher(new DesEdeEngine())));

                case "PBEWITHSHAAND128BITRC2-CBC":
                case "PBEWITHSHAAND40BITRC2-CBC":
                    return(new PaddedBufferedBlockCipher(
                               new CbcBlockCipher(new RC2Engine())));

                case "PBEWITHSHAAND128BITAES-CBC-BC":
                case "PBEWITHSHAAND192BITAES-CBC-BC":
                case "PBEWITHSHAAND256BITAES-CBC-BC":
                case "PBEWITHSHA256AND128BITAES-CBC-BC":
                case "PBEWITHSHA256AND192BITAES-CBC-BC":
                case "PBEWITHSHA256AND256BITAES-CBC-BC":
                case "PBEWITHMD5AND128BITAES-CBC-OPENSSL":
                case "PBEWITHMD5AND192BITAES-CBC-OPENSSL":
                case "PBEWITHMD5AND256BITAES-CBC-OPENSSL":
                    return(new PaddedBufferedBlockCipher(
                               new CbcBlockCipher(new AesFastEngine())));

                case "PBEWITHSHA1ANDDES-CBC":
                    return(new PaddedBufferedBlockCipher(
                               new CbcBlockCipher(new DesEngine())));

                case "PBEWITHSHA1ANDRC2-CBC":
                    return(new PaddedBufferedBlockCipher(
                               new CbcBlockCipher(new RC2Engine())));
                }
            }



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

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

            switch (parts[0])
            {
            case "AES":
                blockCipher = new AesFastEngine();
                break;

            case "ARC4":
                streamCipher = new RC4Engine();
                break;

            case "BLOWFISH":
                blockCipher = new BlowfishEngine();
                break;

            case "CAMELLIA":
                blockCipher = new CamelliaEngine();
                break;

            case "CAST5":
                blockCipher = new Cast5Engine();
                break;

            case "CAST6":
                blockCipher = new Cast6Engine();
                break;

            case "DES":
                blockCipher = new DesEngine();
                break;

            case "DESEDE":
                blockCipher = new DesEdeEngine();
                break;

            case "ELGAMAL":
                asymBlockCipher = new ElGamalEngine();
                break;

            case "GOST28147":
                blockCipher = new Gost28147Engine();
                break;

            case "HC128":
                streamCipher = new HC128Engine();
                break;

            case "HC256":
                streamCipher = new HC256Engine();
                break;

#if INCLUDE_IDEA
            case "IDEA":
                blockCipher = new IdeaEngine();
                break;
#endif
            case "NOEKEON":
                blockCipher = new NoekeonEngine();
                break;

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

            case "RC2":
                blockCipher = new RC2Engine();
                break;

            case "RC5":
                blockCipher = new RC532Engine();
                break;

            case "RC5-64":
                blockCipher = new RC564Engine();
                break;

            case "RC6":
                blockCipher = new RC6Engine();
                break;

            case "RIJNDAEL":
                blockCipher = new RijndaelEngine();
                break;

            case "RSA":
                asymBlockCipher = new RsaBlindedEngine();
                break;

            case "SALSA20":
                streamCipher = new Salsa20Engine();
                break;

            case "SEED":
                blockCipher = new SeedEngine();
                break;

            case "SERPENT":
                blockCipher = new SerpentEngine();
                break;

            case "SKIPJACK":
                blockCipher = new SkipjackEngine();
                break;

            case "TEA":
                blockCipher = new TeaEngine();
                break;

            case "TWOFISH":
                blockCipher = new TwofishEngine();
                break;

            case "VMPC":
                streamCipher = new VmpcEngine();
                break;

            case "VMPC-KSA3":
                streamCipher = new VmpcKsa3Engine();
                break;

            case "XTEA":
                blockCipher = new XteaEngine();
                break;

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

            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");
                }

                switch (parts[2])
                {
                case "NOPADDING":
                    padded = false;
                    break;

                case "":
                case "RAW":
                    break;

                case "ISO10126PADDING":
                case "ISO10126D2PADDING":
                case "ISO10126-2PADDING":
                    padding = new ISO10126d2Padding();
                    break;

                case "ISO7816-4PADDING":
                case "ISO9797-1PADDING":
                    padding = new ISO7816d4Padding();
                    break;

                case "ISO9796-1":
                case "ISO9796-1PADDING":
                    asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
                    break;

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

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

                case "OAEPWITHSHA1ANDMGF1PADDING":
                case "OAEPWITHSHA-1ANDMGF1PADDING":
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
                    break;

                case "OAEPWITHSHA224ANDMGF1PADDING":
                case "OAEPWITHSHA-224ANDMGF1PADDING":
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
                    break;

                case "OAEPWITHSHA256ANDMGF1PADDING":
                case "OAEPWITHSHA-256ANDMGF1PADDING":
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
                    break;

                case "OAEPWITHSHA384ANDMGF1PADDING":
                case "OAEPWITHSHA-384ANDMGF1PADDING":
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
                    break;

                case "OAEPWITHSHA512ANDMGF1PADDING":
                case "OAEPWITHSHA-512ANDMGF1PADDING":
                    asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
                    break;

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

                case "PKCS5":
                case "PKCS5PADDING":
                case "PKCS7":
                case "PKCS7PADDING":
                    // NB: Padding defaults to Pkcs7Padding already
                    break;

                case "TBCPADDING":
                    padding = new TbcPadding();
                    break;

                case "WITHCTS":
                    cts = true;
                    break;

                case "X9.23PADDING":
                case "X923PADDING":
                    padding = new X923Padding();
                    break;

                case "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;

                switch (modeName)
                {
                case "":
                case "ECB":
                case "NONE":
                    break;

                case "CBC":
                    blockCipher = new CbcBlockCipher(blockCipher);
                    break;

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

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

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

                case "CTR":
                    blockCipher = new SicBlockCipher(blockCipher);
                    break;

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

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

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

                case "GOFB":
                    blockCipher = new GOfbBlockCipher(blockCipher);
                    break;

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

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

                case "OPENPGPCFB":
                    blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
                    break;

                case "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.");
                }
            }

            if (aeadBlockCipher != null)
            {
                if (cts)
                {
                    throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
                }
                if (padded && parts.Length > 1 && 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 (!padded || blockCipher.IsPartialBlockOkay)
                {
                    return(new BufferedBlockCipher(blockCipher));
                }

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

                return(new PaddedBufferedBlockCipher(blockCipher));
            }

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

            throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
        }
Пример #31
0
        public static ArrayLease <byte> EncryptBytes(ArraySegment <byte> plaintext, ArraySegment <byte> key, out int count)
        {
            // Blowfish encrypts 8 bytes at a time
            int leftover = plaintext.Count & 7;

            count = (plaintext.Count + 7) & ~7; // branchless version of: n - (n % 8) + 8

            // if there's leftover we'll need another extra 8 bytes to hold the input
            // note that this should not be part of the outputted array,
            // so store it in a new variable
            int capacity = count + ((leftover + 7) & ~7);

            Debug.Assert(leftover == 0 ^ capacity != plaintext.Count);

            var engine       = new BlowfishEngine();
            var keyParameter = new KeyParameter(key.Array, key.Offset, key.Count);

            engine.Init(forEncryption: true, parameters: keyParameter);

            var lease = ArrayPool <byte> .Shared.Lease(capacity);

            try
            {
                int    i      = plaintext.Offset;
                int    j      = 0;
                byte[] input  = plaintext.Array;
                byte[] output = lease.Array;

                // Process each block of bytes
                while (i + 7 < plaintext.Count)
                {
                    engine.ProcessBlock(input, i, output, j);

                    i += 8;
                    j += 8;
                }

                Debug.Assert(
                    i + leftover == plaintext.Count &&
                    leftover >= 0 &&
                    leftover < 8);

                if (leftover != 0)
                {
                    // Handle the leftover input bytes

                    Debug.Assert(
                        count > plaintext.Count &&
                        (count % 8) == 0 &&
                        capacity == count + 8);

                    // Copy over the remaining input data to the end of the output array
                    int inputIndex = i, outputIndex = j + 8;
                    while (inputIndex < plaintext.Count)
                    {
                        output[outputIndex++] = input[inputIndex++];
                    }

                    // Since this is a rented array, clear any extraneous data at the end
                    // Use a regular while loop, since it's less than 8 bytes
                    Debug.Assert(
                        outputIndex <= capacity &&
                        capacity - outputIndex < 8);
                    while (outputIndex < capacity)
                    {
                        output[outputIndex++] = 0;
                    }

                    engine.ProcessBlock(output, j + 8, output, j);
                }
            }
            catch
            {
                lease.Dispose();
                throw;
            }

            return(lease);
        }