예제 #1
0
        /// <summary>
        /// Encapsulates the specified links into an RSDF container.
        /// </summary>
        /// <param name="links">The links.</param>
        /// <returns>
        /// Base-16-encoded RSDF container.
        /// </returns>
        public static string CreateRSDF(string[] links)
        {
            var aes = new AesEngine();
            var cfb = new CfbBlockCipher(aes, 8);
            var pad = new BufferedBlockCipher(cfb);
            var sb  = new StringBuilder();

            pad.Init(true, new ParametersWithIV(new KeyParameter(RSDFKey), RSDFIV));

            foreach (var link in links)
            {
                var input  = Encoding.UTF8.GetBytes(link);
                var output = new byte[input.Length];

                for (var i = 0; i < input.Length; i++)
                {
                    output[i] = pad.ProcessByte(input[i])[0];
                }

                sb.Append(Convert.ToBase64String(output));
                sb.Append(Environment.NewLine);
            }

            return(BitConverter.ToString(Encoding.ASCII.GetBytes(sb.ToString())).Replace("-", string.Empty));
        }
예제 #2
0
        private void InitCiphers()
        {
            CfbBlockCipher encryptor = new CfbBlockCipher(new AesEngine(), 8);
            CfbBlockCipher decryptor = new CfbBlockCipher(new AesEngine(), 8);

            encryptor.Init(true, new ParametersWithIV(new KeyParameter(SharedKey), SharedKey));
            decryptor.Init(false, new ParametersWithIV(new KeyParameter(SharedKey), SharedKey));
            encStream = new StreamBlockCipher(encryptor);
            decStream = new StreamBlockCipher(decryptor);
        }
예제 #3
0
        internal static IBufferedCipher CreateBufferedCipher(string name, AlgorithmMode algorithmMode, IParametersWithIV <IParameters <Algorithm>, Algorithm> parameters, bool forEncryption, IEngineProvider <Internal.IBlockCipher> cipherProvider)
        {
            Internal.IBlockCipher baseCipher = cipherProvider.CreateEngine(GetUsage(forEncryption, algorithmMode));
            Internal.IBlockCipher cipher;

            switch (algorithmMode)
            {
            case AlgorithmMode.CBC:
                cipher = new CbcBlockCipher(baseCipher);
                break;

            case AlgorithmMode.CS1:
                return(new NistCtsBlockCipher(NistCtsBlockCipher.CS1, baseCipher));

            case AlgorithmMode.CS2:
                return(new NistCtsBlockCipher(NistCtsBlockCipher.CS2, baseCipher));

            case AlgorithmMode.CS3:
                return(new NistCtsBlockCipher(NistCtsBlockCipher.CS3, baseCipher));

            case AlgorithmMode.CFB8:
                cipher = new CfbBlockCipher(baseCipher, 8);
                break;

            case AlgorithmMode.CFB64:
                cipher = new CfbBlockCipher(baseCipher, 64);
                break;

            case AlgorithmMode.CFB128:
                cipher = new CfbBlockCipher(baseCipher, 128);
                break;

            case AlgorithmMode.OpenPGPCFB:
                cipher = new OpenPgpCfbBlockCipher(baseCipher);
                break;

            case AlgorithmMode.OFB64:
                cipher = new OfbBlockCipher(baseCipher, 64);
                break;

            case AlgorithmMode.OFB128:
                cipher = new OfbBlockCipher(baseCipher, 128);
                break;

            case AlgorithmMode.CTR:
                cipher = new SicBlockCipher(baseCipher);
                break;

            default:
                throw new ArgumentException("Unknown algorithm mode passed to " + name + ".Provider: " + algorithmMode);
            }

            return(new BufferedBlockCipher(cipher));
        }
예제 #4
0
        /// <summary>
        ///     Encrypt scoped PDU
        /// </summary>
        /// <param name="unencryptedData">Unencrypted scoped PDU byte array</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="engineBoots">Engine boots.</param>
        /// <param name="engineTime">Engine time.</param>
        /// <param name="privacyParameters">
        ///     Privacy parameters out buffer. This field will be filled in with information
        ///     required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        ///     in the USM header to store this information
        /// </param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Thrown when encryption key is null or length of the encryption key is too
        ///     short.
        /// </exception>
        internal byte[] Encrypt(byte[] unencryptedData, byte[] key, int engineBoots, int engineTime,
                                byte[] privacyParameters)
        {
            // check the key before doing anything else
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (key.Length < KeyBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(key), "Invalid key length.");
            }

            if (unencryptedData == null)
            {
                throw new ArgumentNullException(nameof(unencryptedData));
            }

            // Set privacy parameters to the local 64 bit salt value
            var iv         = new byte[16];
            var bootsBytes = BitConverter.GetBytes(engineBoots);

            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            var timeBytes = BitConverter.GetBytes(engineTime);

            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength);

            // Resize the key, if necessary, to the required length
            Array.Resize(ref key, KeyBytes);

            // Encrypt using BouncyCastle
            var blockCipher      = new CfbBlockCipher(new AesEngine(), 128);
            var paddedCipher     = new PaddedBufferedBlockCipher(blockCipher, new ZeroBytePadding());
            var cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);

            paddedCipher.Init(true, cipherParameters);
            var encryptedData = paddedCipher.DoFinal(unencryptedData);

            // Trim off padding, if necessary
            Array.Resize(ref encryptedData, unencryptedData.Length);

            return(encryptedData);
        }
        /// <summary>
        /// Buisl a BlockCipher with a mode
        /// </summary>
        /// <param name="blockCipher">BlockCipher loaded with the algorithm Engine</param>
        /// <param name="mode">SymmetricBlockModes enum, mode name</param>
        /// <returns>BlockCipher with mode loaded</returns>
        private IBlockCipher getCipherMode(IBlockCipher blockCipher, SymmetricBlockMode mode)
        {
            IBlockCipher bc = null;

            switch (mode)
            {
            case SymmetricBlockMode.ECB:
            case SymmetricBlockMode.NONE:
                bc = blockCipher;
                break;

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

            case SymmetricBlockMode.CFB:
                bc = new CfbBlockCipher(blockCipher, blockCipher.GetBlockSize());
                break;

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

            case SymmetricBlockMode.CTS:
                bc = new CbcBlockCipher(blockCipher);
                break;

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

            case SymmetricBlockMode.OFB:
                bc = new OfbBlockCipher(blockCipher, blockCipher.GetBlockSize());
                break;

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

            case SymmetricBlockMode.SIC:
                if (blockCipher.GetBlockSize() < 16)
                {
                    this.error.setError("SB016",
                                        "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;
            }
            return(bc);
        }
예제 #6
0
파일: DES.cs 프로젝트: egg82/FileEncryptor
        //private
        private static byte[] encryptDecrypt(byte[] input, byte[] key, byte[] iv, BlockMode mode, BlockPadding padding, bool encrypt)
        {
            DesEdeEngine        engine = new DesEdeEngine();
            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);
        }
예제 #7
0
        private IBufferedCipher createCipher(bool forEncryption)
        {
//			IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CFB/NoPadding");

            IBlockCipher blockCipher = new AesEngine();
            int          bits        = 8 * blockCipher.GetBlockSize(); // TODO Is this right?

            blockCipher = new CfbBlockCipher(blockCipher, bits);
            IBufferedCipher cipher = new BufferedBlockCipher(blockCipher);

//			SecureRandom random = new SecureRandom();
            byte[] keyBytes = new byte[32];
            //random.NextBytes(keyBytes);
            KeyParameter key = new KeyParameter(keyBytes);

            byte[] iv = new byte[cipher.GetBlockSize()];
            //random.NextBytes(iv);

            cipher.Init(forEncryption, new ParametersWithIV(key, iv));

            return(cipher);
        }
예제 #8
0
        private static PaddedBufferedBlockCipher CreateCipher(string encryptionMode, int segmentSize)
        {
            var engine = new RC6Engine();
            var padding = new Pkcs7Padding();
            IBlockCipher cipherWithoutPadding = null;
            switch (encryptionMode)
            {
                case "ECB":
                    cipherWithoutPadding = engine;
                    break;
                case "CBC":
                    cipherWithoutPadding = new CbcBlockCipher(engine);
                    break;
                case "CFB":
                    cipherWithoutPadding = new CfbBlockCipher(engine, segmentSize);
                    break;
                case "OFB":
                    cipherWithoutPadding = new OfbBlockCipher(engine, segmentSize);
                    break;
            }

            return new PaddedBufferedBlockCipher(cipherWithoutPadding, padding);
        }
        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.");
        }
예제 #10
0
        public void Setup()
        {
            var engine = new AesEngine();

            _subject = new CfbBlockCipher(engine, new ShiftRegisterStrategyByte(engine));
        }
예제 #11
0
        public void EncryptToFile(byte[] sessionKey)
        {
            File.AppendAllText(MainWindow.OutputFile, Environment.NewLine);

            using (var input = File.Open(MainWindow.InputFile, FileMode.Open))
                using (var fs = File.Open(MainWindow.OutputFile, FileMode.Append))
                {
                    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new RC6Engine());

                    switch (Mode)
                    {
                    case "CFB":
                    {
                        CfbBlockCipher cipher = new CfbBlockCipher(new RC6Engine(), SubblockSize);
                        aes = new PaddedBufferedBlockCipher(cipher);
                        break;
                    }

                    case "OFB":
                    {
                        OfbBlockCipher cipher = new OfbBlockCipher(new RC6Engine(), SubblockSize);
                        aes = new PaddedBufferedBlockCipher(cipher);
                        break;
                    }

                    case "CBC":
                    {
                        CbcBlockCipher cipher = new CbcBlockCipher(new RC6Engine());
                        aes = new PaddedBufferedBlockCipher(cipher);
                        break;
                    }

                    case "ECB":
                    {
                        aes = new PaddedBufferedBlockCipher(new RC6Engine());
                        aes.Init(true, new KeyParameter(sessionKey));
                        break;
                    }
                    }


                    if (Mode != "ECB")
                    {
                        var keyParameter = new KeyParameter(sessionKey);
                        var parameters   = new ParametersWithIV(keyParameter, InitialVector);
                        aes.Init(true, parameters);
                    }


                    var buffer       = new byte[aes.GetBlockSize()];
                    var outputBuffer = new byte[aes.GetBlockSize() + aes.GetOutputSize(buffer.Length)];

                    int inCount  = 0;
                    int outCount = 0;


                    long  blocksCounter = input.Length / buffer.Length + 1;
                    long  i             = 0;
                    float percent;

                    while ((inCount = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outCount = aes.ProcessBytes(buffer, 0, inCount, outputBuffer, 0);
                        fs.Write(outputBuffer, 0, outCount);
                        i++;

                        if (EncryptProgress != null)
                        {
                            percent = (float)i / blocksCounter * 100;
                            EncryptProgress((int)percent);
                        }
                    }

                    outCount = aes.DoFinal(outputBuffer, 0);
                    fs.Write(outputBuffer, 0, outCount);
                }
        }
        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.");
        }
예제 #13
0
        public void DecryptFromFile(byte[] sessionKey)
        {
            using (var input = File.Open("zaszyfrowany.tmp", FileMode.Open))
                using (var fs = File.Open(MainWindow.OutputFile, FileMode.Create))
                {
                    BufferedBlockCipher aes = new BufferedBlockCipher(new RC6Engine());

                    if (IsPasswordValid)
                    {
                        switch (Mode)
                        {
                        case "CFB":
                        {
                            CfbBlockCipher cipher = new CfbBlockCipher(new RC6Engine(), SubblockSize);
                            aes = new PaddedBufferedBlockCipher(cipher);
                            break;
                        }

                        case "OFB":
                        {
                            OfbBlockCipher cipher = new OfbBlockCipher(new RC6Engine(), SubblockSize);
                            aes = new PaddedBufferedBlockCipher(cipher);
                            break;
                        }

                        case "CBC":
                        {
                            CbcBlockCipher cipher = new CbcBlockCipher(new RC6Engine());
                            aes = new PaddedBufferedBlockCipher(cipher);
                            break;
                        }

                        case "ECB":
                        {
                            aes = new PaddedBufferedBlockCipher(new RC6Engine());
                            aes.Init(false, new KeyParameter(sessionKey));
                            break;
                        }
                        }

                        if (Mode != "ECB")
                        {
                            var keyParam   = new KeyParameter(sessionKey);
                            var parameters = new ParametersWithIV(keyParam, InitialVector);
                            aes.Init(false, parameters);
                        }
                    }

                    else
                    {
                        aes = new BufferedBlockCipher(new RC6Engine());
                        aes.Init(false, new KeyParameter(sessionKey));
                    }

                    var buffer    = new byte[aes.GetBlockSize()];
                    var outBuffer = new byte[aes.GetBlockSize() + aes.GetOutputSize(buffer.Length)];

                    int inCount  = 0;
                    int outCount = 0;

                    long  blocksCounter = input.Length / buffer.Length + 1;
                    long  i             = 0;
                    float percent;

                    while ((inCount = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outCount = aes.ProcessBytes(buffer, 0, inCount, outBuffer, 0);
                        fs.Write(outBuffer, 0, outCount);
                        i++;

                        if (DecryptProgress != null)
                        {
                            percent = (float)i / blocksCounter * 100;
                            DecryptProgress((int)percent);
                        }
                    }

                    try
                    {
                        outCount = aes.DoFinal(outBuffer, 0);
                        fs.Write(outBuffer, 0, outCount);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("BŁAD ZAPISU SZYFRU DO PLIKU!!!");
                    }
                }
        }
예제 #14
0
        public virtual ITestResult Perform()
        {
            KeyParameter key = new KeyParameter(Hex.Decode("0011223344556677"));

            byte[] input = Hex.Decode("4e6f7720");
            byte[] out1  = new byte[4];
            byte[] out2  = new byte[4];


            IBlockCipher ofb = new OfbBlockCipher(new DesEngine(), 32);

            ofb.Init(true, new ParametersWithIV(key, Hex.Decode("1122334455667788")));

            ofb.ProcessBlock(input, 0, out1, 0);

            ofb.Init(false, new ParametersWithIV(key, Hex.Decode("1122334455667788")));
            ofb.ProcessBlock(out1, 0, out2, 0);

            if (!Arrays.AreEqual(out2, input))
            {
                return(new SimpleTestResult(false, Name + ": test 1 - in != out"));
            }

            ofb.Init(true, new ParametersWithIV(key, Hex.Decode("11223344")));

            ofb.ProcessBlock(input, 0, out1, 0);

            ofb.Init(false, new ParametersWithIV(key, Hex.Decode("0000000011223344")));
            ofb.ProcessBlock(out1, 0, out2, 0);

            if (!Arrays.AreEqual(out2, input))
            {
                return(new SimpleTestResult(false, Name + ": test 2 - in != out"));
            }

            IBlockCipher cfb = new CfbBlockCipher(new DesEngine(), 32);

            cfb.Init(true, new ParametersWithIV(key, Hex.Decode("1122334455667788")));

            cfb.ProcessBlock(input, 0, out1, 0);

            cfb.Init(false, new ParametersWithIV(key, Hex.Decode("1122334455667788")));
            cfb.ProcessBlock(out1, 0, out2, 0);

            if (!Arrays.AreEqual(out2, input))
            {
                return(new SimpleTestResult(false, Name + ": test 3 - in != out"));
            }

            cfb.Init(true, new ParametersWithIV(key, Hex.Decode("11223344")));

            cfb.ProcessBlock(input, 0, out1, 0);

            cfb.Init(false, new ParametersWithIV(key, Hex.Decode("0000000011223344")));
            cfb.ProcessBlock(out1, 0, out2, 0);

            if (!Arrays.AreEqual(out2, input))
            {
                return(new SimpleTestResult(false, Name + ": test 4 - in != out"));
            }

            return(new SimpleTestResult(true, Name + ": Okay"));
        }
예제 #15
0
        } // DecryptArray

        /*
         * private static bool DONT_USE_AESEncDecArray(bool bEncryptorDecrypt, ref byte[] aData, byte[] aAESKey, byte[] aIV = null)
         * {
         *  bool bRet = true;
         *  try
         *  {
         *      if (   (aData == null)
         || ((bEncryptorDecrypt == true)  && (aData.Length == 0))
         || ((bEncryptorDecrypt == false) && (aData.Length <= 16))   //Must be longer than the IV, when decrypting
         || (aAESKey.Length != 32)
         || ((aIV != null) && (aIV.Length != 16)))
         ||         return false;
         ||
         ||     // Instantiate a new Aes object to perform string symmetric encryption
         ||
         ||     using (Rijndael AES = RijndaelManaged.Create())  //Not FIPS compliant.  :(
         ||     //using (Aes AES = Aes.Create())  //Issues! Not compatible with AES CPP implementation
         ||     {
         ||         //Construct the IV
         ||         bool bIVWasNull = (aIV == null);
         ||         if (bIVWasNull)
         ||             aIV = new byte[16];
         ||
         ||         if (bEncryptorDecrypt)
         ||         {
         ||             if (bIVWasNull)
         ||                 aIV.FillRandom();  //when encrypting: new IV
         ||         }
         ||         else
         ||             Array.Copy(aData, aData.Length - 16, aIV, 0, 16);  //when decrypting: use the IV thats the last 16 bytes of the data.
         ||
         ||         // Set mode, padding, key and IV
         ||         AES.Mode      = CipherMode.CFB;
         ||         AES.Padding   = PaddingMode.None;
         ||         AES.Key       = aAESKey;
         ||         AES.IV        = aIV;
         ||         AES.BlockSize = 128; //16 bytes
         ||
         ||         // Instantiate a new MemoryStream object to contain the encrypted bytes
         ||         MemoryStream ms = new MemoryStream();
         ||         //Dispose not required on MemoryStream, but gives a compiler warning/error when in a 'using' as CryptoStream below disposes of it as well.
         ||         //using (MemoryStream ms = new MemoryStream())
         ||         {
         ||             // Instantiate a new encryptor/decryptor from our Aes object
         ||             using (ICryptoTransform aesCryptor = bEncryptorDecrypt ? AES.CreateEncryptor() : AES.CreateDecryptor())
         ||             {
         ||                 // Instantiate a new CryptoStream object to process the data and write it to the memory stream
         ||                 using (CryptoStream cs = new CryptoStream(ms, aesCryptor, CryptoStreamMode.Write))
         ||                 {
         ||                     // Encrypt/decrypt the input
         ||                     int iCount = bEncryptorDecrypt ? aData.Length : aData.Length - 16;
         ||                     cs.Write(aData, 0, iCount);  //-16, ignore the IV
         ||
         ||                     //Add padding
         ||                     int iPadded = -1;
         ||                     {
         ||                         //Padding.. .Why do we have to do this!
         ||                         int iBlockSizeInBytes = AES.BlockSize / 8;  //Bits to bytes.
         ||
         ||                         int iCompleteBlock = iBlockSizeInBytes - (iCount % iBlockSizeInBytes);
         ||                         if (iCompleteBlock < iBlockSizeInBytes)
         ||                         {
         ||                             iPadded = iCompleteBlock;
         ||                             byte[] aZero = new byte[iPadded];
         ||                             cs.Write(aZero, 0, iPadded);  //-16, ignore the IV
         ||                         }
         ||
         ||                     }
         ||
         ||                     // Complete the encrypt/decrypt process
         ||                     cs.FlushFinalBlock();
         ||
         ||                     //Remove Padding
         ||                     if (iPadded > 0)
         ||                     {
         ||
         ||                         long iLen = ms.Length;
         ||                         if (iLen > iPadded)
         ||                             ms.SetLength(iLen - iPadded);
         ||                     }
         ||
         ||                     if (bEncryptorDecrypt)
         ||                         ms.Write(aIV, 0, aIV.Length);
         ||
         ||                     // Convert the encrypted/decrypted data from a MemoryStream to a byte array
         ||                     aData = ms.ToArray();
         ||                 }
         ||             }
         ||         }
         ||     }
         || }
         || catch (Exception e) { bRet = false;  e.CatchMessage().TraceError("EncDecArray(): "); }
         || return bRet;
         ||} // DONT_USE_AESEncDecArray
         */

        private static bool AESEncDecArray(bool bEncryptorDecrypt, ref byte[] aData, byte[] aAESKey, byte[] aIV = null)
        {
            bool bRet = true;

            try
            {
                if ((aData == null) ||
                    ((bEncryptorDecrypt == true) && (aData.Length == 0)) ||
                    ((bEncryptorDecrypt == false) && (aData.Length <= 16)) ||   //Must be longer than the IV, when decrypting
                    (aAESKey.Length != 32) ||
                    ((aIV != null) && (aIV.Length != 16)))
                {
                    return(false);
                }

                //Construct the IV
                bool bIVWasNull = (aIV == null);
                if (bIVWasNull)
                {
                    aIV = new byte[16];
                }

                int iDataLength = 0;
                if (bEncryptorDecrypt)
                {
                    iDataLength = aData.Length;
                    if (bIVWasNull)
                    {
                        aIV.FillRandom();  //when encrypting: new IV
                    }
                }
                else
                {
                    Array.Copy(aData, aData.Length - 16, aIV, 0, 16);  //when decrypting: use the IV thats the last 16 bytes of the data.
                    iDataLength = aData.Length - 16;
                }

                CfbBlockCipher cfb = new CfbBlockCipher(new AesEngine(), 128);
                cfb.Init(bEncryptorDecrypt, new ParametersWithIV(new KeyParameter(aAESKey), aIV));

                int iBlockSize = cfb.GetBlockSize();
                for (int i = 0; i < iDataLength; i += iBlockSize)
                {
                    int iRet       = 0;
                    int iRemaining = iDataLength - i;
                    if (iRemaining < iBlockSize)
                    {
                        //Last partial block
                        byte[] aIn  = new byte[iBlockSize];
                        byte[] aOut = new byte[iBlockSize];
                        Array.Copy(aData, i, aIn, 0, iRemaining);

                        if (bEncryptorDecrypt)
                        {
                            iRet = cfb.EncryptBlock(aIn, 0, aOut, 0);
                        }
                        else
                        {
                            iRet = cfb.DecryptBlock(aIn, 0, aOut, 0);
                        }
                        Array.Copy(aOut, 0, aData, i, iRemaining);
                        continue;
                    }

                    if (bEncryptorDecrypt)
                    {
                        iRet = cfb.EncryptBlock(aData, i, aData, i);
                    }
                    else
                    {
                        iRet = cfb.DecryptBlock(aData, i, aData, i);
                    }
                }

                if (bEncryptorDecrypt)
                {
                    //Append IV.
                    Array.Resize(ref aData, iDataLength + 16);
                    Array.Copy(aIV, 0, aData, iDataLength, 16);
                }
                else
                {
                    //Remove IV
                    Array.Resize(ref aData, iDataLength);
                }
            }
            catch (Exception e) { bRet = false; e.CatchMessage().TraceError("AESEncDecArray(): "); }
            return(bRet);
        } // AESEncDecArray
        /// <summary>
        /// Decrypt scoped PDU.
        /// </summary>
        /// <param name="encryptedData">Source data buffer</param>
        /// <param name="engineBoots">Engine boots.</param>
        /// <param name="engineTime">Engine time.</param>
        /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param>
        /// <param name="privacyParameters">Privacy parameters extracted from USM header</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters
        /// argument is null or length other then 8 bytes</exception>
        internal byte[] Decrypt(byte[] encryptedData, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (encryptedData == null)
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }

            if (key.Length < KeyBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(key), "Invalid key length.");
            }

            // Set privacy parameters to the local 64 bit salt value
            var iv         = new byte[16];
            var bootsBytes = BitConverter.GetBytes(engineBoots);

            iv[0] = bootsBytes[3];
            iv[1] = bootsBytes[2];
            iv[2] = bootsBytes[1];
            iv[3] = bootsBytes[0];
            var timeBytes = BitConverter.GetBytes(engineTime);

            iv[4] = timeBytes[3];
            iv[5] = timeBytes[2];
            iv[6] = timeBytes[1];
            iv[7] = timeBytes[0];

            // Copy salt value to the iv array
            Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength);

            // Resize the key, if necessary, to the required length
            Array.Resize(ref key, KeyBytes);

            // Pad encrypted data to a multiple of 16 bytes
            byte[] encryptedDataPadded = encryptedData;
            if (encryptedData.Length % KeyBytes != 0)
            {
                var div       = (int)Math.Floor(encryptedData.Length / (double)16);
                var newLength = (div + 1) * 16;
                encryptedDataPadded = new byte[newLength];
                Buffer.BlockCopy(encryptedData, 0, encryptedDataPadded, 0, encryptedData.Length);
            }

            // Decrypt using BouncyCastle
            var blockCipher      = new CfbBlockCipher(new AesEngine(), 128);
            var paddedCipher     = new PaddedBufferedBlockCipher(blockCipher, new ZeroBytePadding());
            var cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);

            paddedCipher.Init(false, cipherParameters);
            var decryptedData = paddedCipher.DoFinal(encryptedDataPadded);

            // Trim off padding, if necessary
            Array.Resize(ref decryptedData, encryptedData.Length);

            return(decryptedData);
        }
예제 #17
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.");
        }
예제 #18
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.");
        }