コード例 #1
0
        /// <summary>
        /// Buils an AEADBlockCipher engine
        /// </summary>
        /// <param name="blockCipher">BlockCipher engine</param>
        /// <param name="mode">SymmetricBlockModes enum, symmetric block mode name</param>
        /// <returns>AEADBlockCipher loaded with a given BlockCipher</returns>
        private IAeadBlockCipher getAEADCipherMode(IBlockCipher blockCipher, SymmetricBlockMode mode)
        {
            IAeadBlockCipher bc = null;

            switch (mode)
            {
            case SymmetricBlockMode.AEAD_CCM:
                bc = new CcmBlockCipher(blockCipher);
                break;

            case SymmetricBlockMode.AEAD_EAX:
                bc = new EaxBlockCipher(blockCipher);
                break;

            case SymmetricBlockMode.AEAD_GCM:
                bc = new GcmBlockCipher(blockCipher);
                break;

            case SymmetricBlockMode.AEAD_KCCM:
                bc = new KCcmBlockCipher(blockCipher);
                break;

            default:
                this.error.setError("SB017", "AEADCipher " + mode + " not recognised.");
                break;
            }
            return(bc);
        }
コード例 #2
0
        public void ShouldReturnCorrectMac(
            int keySize, int tagLength,
            BitString serverId, BitString iutId,
            BitString nonce,
            BitString serverPublicKey, BitString iutPublicKey,
            BitString derivedKeyingMaterial,
            BitString expectedMacData, BitString expectedTag)
        {
            var ccm = new CcmBlockCipher(new AesEngine(), new ModeBlockCipherFactory(), new AES_CCMInternals());

            var p = new KeyConfirmationParameters(
                KeyAgreementRole.InitiatorPartyU,
                KeyConfirmationRole.Provider,
                KeyConfirmationDirection.Bilateral,
                KeyAgreementMacType.AesCcm, // note this doesn't matter for the scope of this test
                keySize,
                tagLength,
                iutId,
                serverId,
                iutPublicKey,
                serverPublicKey,
                derivedKeyingMaterial,
                nonce
            );

            _subject = new KeyConfirmationAesCcm(new KeyConfirmationMacDataCreator(), p, ccm);

            var result = _subject.ComputeMac();

            Assert.That(result.Success);
            Assert.AreEqual(expectedMacData.ToHex(), result.MacData.ToHex(), nameof(expectedMacData));
            Assert.AreEqual(expectedTag.ToHex(), result.Mac.ToHex(), nameof(expectedTag));
        }
コード例 #3
0
ファイル: SjclManaged.cs プロジェクト: Shidzy2/bitgo-dotnet
        public string Decrypt(string json, string password)
        {
            var jsonObj = JsonConvert.DeserializeObject <SjclJson>(json);
            var v       = jsonObj.V;
            var adata   = Convert.FromBase64String(jsonObj.AData);
            var iv      = Convert.FromBase64String(jsonObj.IV);
            var salt    = Convert.FromBase64String(jsonObj.Salt);
            var ks      = jsonObj.KS;
            var ts      = jsonObj.TS;
            var iter    = jsonObj.Iter;
            var ct      = Convert.FromBase64String(jsonObj.CT);
            // var cipher = json.Cipher;
            // var mode = json.Mode;
            var key = GenKeyBytes(password, salt, ks, iter);

            var nonSecretPayload = new byte[] { };

            var cipher     = new CcmBlockCipher(new AesFastEngine());
            var parameters = new CcmParameters(
                new KeyParameter(key), ts, iv.Take(13).ToArray(), nonSecretPayload);

            cipher.Init(false, parameters);

            var plainText = new byte[cipher.GetOutputSize(ct.Length)];
            var len       = cipher.ProcessBytes(ct, 0, ct.Length, plainText, 0);

            cipher.DoFinal(plainText, len);
            return(Encoding.UTF8.GetString(plainText));
        }
コード例 #4
0
        private void ivParamTest(
            int count,
            CcmBlockCipher ccm,
            byte[]                  k,
            byte[]                  n)
        {
            byte[] p = Encoding.ASCII.GetBytes("hello world!!");

            ccm.Init(true, new ParametersWithIV(new KeyParameter(k), n));

            byte[] enc = new byte[p.Length + 8];

            int len = ccm.ProcessBytes(p, 0, p.Length, enc, 0);

            len += ccm.DoFinal(enc, len);

            ccm.Init(false, new ParametersWithIV(new KeyParameter(k), n));

            byte[] tmp = new byte[enc.Length];

            len = ccm.ProcessBytes(enc, 0, enc.Length, tmp, 0);

            len += ccm.DoFinal(tmp, len);

            byte[] dec = new byte[len];

            Array.Copy(tmp, 0, dec, 0, len);

            if (!AreEqual(p, dec))
            {
                Fail("decrypted stream fails to match in test " + count);
            }
        }
コード例 #5
0
        public static string Decrypt(string password, string data)
        {
            SJCLBlob ctdata = JsonConvert.DeserializeObject <SJCLBlob>(data);

            if (ctdata.Cipher != "aes" || ctdata.Mode != "ccm")
            {
                throw new InvalidOperationException("Unsupported cipher or mode.");
            }
            byte[] cipherText           = DecodeBase64(ctdata.CipherText);
            var    derivedMacParameters = DeriveKey(password, ctdata);

            var l = FindIVLen(cipherText.Length);

            byte[] iv = new byte[l];
            Array.Copy((Array)DecodeBase64(ctdata.IV), (Array)iv, (int)l);

            var ccmparams = new CcmParameters(derivedMacParameters, ctdata.TagSize, iv, DecodeBase64(ctdata.AuthData));
            var ccmMode   = new CcmBlockCipher(new AesFastEngine());

            ccmMode.Init(false, ccmparams);
            var plainBytes = new byte[ccmMode.GetOutputSize(cipherText.Length)];
            var res        = ccmMode.ProcessBytes(cipherText, 0, cipherText.Length, plainBytes, 0);

            ccmMode.DoFinal(plainBytes, res);
            return(Encoding.UTF8.GetString(plainBytes));
        }
コード例 #6
0
ファイル: FipsAes.cs プロジェクト: NDWX/BouncyCastle.FIPS
            internal override void Evaluate(EngineProvider provider)
            {
                byte[] K = Hex.Decode("404142434445464748494a4b4c4d4e4f");
                byte[] N = Hex.Decode("10111213141516");
                byte[] A = Hex.Decode("0001020304050607");
                byte[] P = Hex.Decode("20212223");
                byte[] C = Hex.Decode("7162015b4dac255d");
                byte[] T = Hex.Decode("6084341b");

                CcmBlockCipher encCipher = new CcmBlockCipher(provider.CreateEngine(EngineUsage.GENERAL));
                CcmBlockCipher decCipher = new CcmBlockCipher(provider.CreateEngine(EngineUsage.GENERAL));
                int            macSize   = T.Length * 8;

                KeyParameter keyParam = new KeyParameter(K);

                encCipher.Init(true, new AeadParameters(keyParam, macSize, N, A));

                byte[] enc = new byte[C.Length];

                int len = encCipher.ProcessBytes(P, 0, P.Length, enc, 0);

                encCipher.DoFinal(enc, len);

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesCcmEnc], enc))
                {
                    Fail("encrypted stream fails to match in self test");
                }

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesCcmEncTag], encCipher.GetMac()))
                {
                    Fail("MAC fails to match in self test encrypt");
                }

                decCipher.Init(false, new AeadParameters(keyParam, macSize, N, A));

                byte[] tmp = new byte[enc.Length];

                len = decCipher.ProcessBytes(enc, 0, enc.Length, tmp, 0);

                len += decCipher.DoFinal(tmp, len);

                byte[] dec = new byte[len];

                Array.Copy(tmp, 0, dec, 0, len);

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesCcmDec], dec))
                {
                    Fail("decrypted stream fails to match in self test");
                }

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesCcmDecTag], decCipher.GetMac()))
                {
                    Fail("MAC fails to match in self test");
                }
            }
コード例 #7
0
ファイル: CCMTest.cs プロジェクト: ekr/hacrypto
        private void checkVectors(
            int count,
            CcmBlockCipher ccm,
            byte[] k,
            int macSize,
            byte[] n,
            byte[] a,
            byte[] p,
            byte[] t,
            byte[] c)
        {
            ccm.Init(true, new AeadParameters(new KeyParameter(k), macSize, n, a));

            byte[] enc = new byte[c.Length];

            int len = ccm.ProcessBytes(p, 0, p.Length, enc, 0);

            len += ccm.DoFinal(enc, len);

//			ccm.Init(true, new CcmParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] enc = ccm.ProcessPacket(p, 0, p.Length);

            if (!AreEqual(c, enc))
            {
                Fail("encrypted stream fails to match in test " + count);
            }

//			ccm.Init(false, new CcmParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] dec = ccm.ProcessPacket(enc, 0, enc.Length);

            ccm.Init(false, new AeadParameters(new KeyParameter(k), macSize, n, a));

            byte[] tmp = new byte[enc.Length];

            len = ccm.ProcessBytes(enc, 0, enc.Length, tmp, 0);

            len += ccm.DoFinal(tmp, len);

            byte[] dec = new byte[len];

            Array.Copy(tmp, 0, dec, 0, len);

            if (!AreEqual(p, dec))
            {
                Fail("decrypted stream fails to match in test " + count);
            }

            if (!AreEqual(t, ccm.GetMac()))
            {
                Fail("MAC fails to match in test " + count);
            }
        }
コード例 #8
0
ファイル: JsonEncrypt.cs プロジェクト: twistys01/ripple-cs
        public JObject Decrypt(string key, JObject json)
        {
            try
            {
                byte[] iv         = Base64.Decode(json.GetValue("iv").ToString());
                byte[] cipherText = Base64.Decode(json.GetValue("ct").ToString());
                byte[] adataBytes = DecodeAdataBytes(json.GetValue("adata").ToString());
                byte[] nonce      = ComputeNonce(iv, cipherText);

                if (json.GetValue("mode").ToString() != "ccm")
                {
                    throw new ApplicationException("Can only decrypt ccm mode encrypted data.");
                }

                KeyParameter keyParam = CreateKey(
                    key,
                    Base64.Decode(json.GetValue("salt").ToString()),
                    json.GetValue("iter").ToObject <int>(),
                    json.GetValue("ks").ToObject <int>());

                var ccm = new AeadParameters(
                    keyParam,
                    MacSize(json.GetValue("ts").ToObject <int>()),
                    nonce,
                    adataBytes);

                var aes = new CcmBlockCipher(new AesFastEngine());
                aes.Init(false, ccm);

                var plainBytes = new byte[aes.GetOutputSize(cipherText.Length)];

                int res = aes.ProcessBytes(
                    cipherText,
                    0,
                    cipherText.Length,
                    plainBytes,
                    0);

                aes.DoFinal(plainBytes, res);
                var text = Encoding.UTF8.GetString(plainBytes);
                return(JObject.Parse(text));
            }
            catch (InvalidCipherTextException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new ApplicationException("Json decryption failed.", e);
            }
        }
コード例 #9
0
        private static MemoryStream Encrypt(Stream source, string fileName, out string seed_encoded, out string ident)
        {
            // Randomly generate a new seed for upload
            byte[] seed = new byte[16];

            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                rngCsp.GetBytes(seed);
            }

            seed_encoded = UrlBase64Encode(seed);

            // Derive the parameters (key, IV, ident) from the seed
            byte[] key, iv;
            DeriveParams(seed, out key, out iv, out ident);

            // Create a new String->String map for JSON blob, and define filename and metadata
            Dictionary <string, string> metadataMap = new Dictionary <string, string>();

            metadataMap["mime"] = Helpers.IsTextFile(fileName) ? "text/plain" : Helpers.GetMimeType(fileName);
            metadataMap["name"] = fileName;

            // Encode the metadata with UTF-16 and a double-null-byte terminator, and append data
            // Unfortunately, the CCM cipher mode can't stream the encryption, and so we have to GetBytes() on the source.
            // We do limit the source to 50MB however
            byte[] data = Encoding.BigEndianUnicode.GetBytes(JsonConvert.SerializeObject(metadataMap)).Concat(new byte[] { 0, 0 }).Concat(source.GetBytes()).ToArray();

            // Calculate the length of the CCM IV and copy it over
            long ccmIVLen = FindIVLen(data.Length);

            byte[] ccmIV = new byte[ccmIVLen];
            Array.Copy(iv, ccmIV, ccmIVLen);

            // Set up the encryption parameters
            KeyParameter   keyParam  = new KeyParameter(key);
            CcmParameters  ccmParams = new CcmParameters(keyParam, MacSize, ccmIV, new byte[0]);
            CcmBlockCipher ccmMode   = new CcmBlockCipher(new AesFastEngine());

            ccmMode.Init(true, ccmParams);

            // Perform the encryption
            byte[] encBytes = new byte[ccmMode.GetOutputSize(data.Length)];
            int    res      = ccmMode.ProcessBytes(data, 0, data.Length, encBytes, 0);

            ccmMode.DoFinal(encBytes, res);

            return(new MemoryStream(encBytes));
        }
コード例 #10
0
ファイル: JsonEncrypt.cs プロジェクト: twistys01/ripple-cs
        public JObject Encrypt(string key, JObject blob, string adata)
        {
            var result = new JObject();
            var random = new SecureRandom();

            var iv   = new byte[32];
            var salt = new byte[8];

            random.NextBytes(salt);
            random.NextBytes(iv);

            try
            {
                byte[] plainBytes = Encoding.UTF8.GetBytes(blob.ToString());
                byte[] adataBytes = Encoding.UTF8.GetBytes(adata);
                byte[] nonce      = ComputeNonce(iv, plainBytes);

                KeyParameter keyParam = CreateKey(key, salt, _iter, _ks);
                var          ccm      = new AeadParameters(keyParam, MacSize(_ts), nonce, adataBytes);

                var aes = new CcmBlockCipher(new AesFastEngine());
                aes.Init(true, ccm);

                var enc = new byte[aes.GetOutputSize(plainBytes.Length)];

                int res = aes.ProcessBytes(plainBytes, 0, plainBytes.Length, enc, 0);

                aes.DoFinal(enc, res);

                result.Add("ct", Base64.ToBase64String(enc));
                result.Add("iv", Base64.ToBase64String(iv));
                result.Add("salt", Base64.ToBase64String(salt));
                result.Add("adata", EncodeAdata(adata));
                result.Add("mode", Mode);
                result.Add("ks", _ks);
                result.Add("iter", _iter);
                result.Add("ts", _ts);

                return(result);
            }
            catch (Exception e)
            {
                throw new ApplicationException("Json encryption failed.", e);
            }
        }
コード例 #11
0
ファイル: SjclManaged.cs プロジェクト: Shidzy2/bitgo-dotnet
        public string Encrypt(string plainText, string password)
        {
            var v    = 1;
            var iter = 10000;
            var ks   = 256;
            var ts   = 64;
            // var mode = "ccm";
            // var cipher = "aes";

            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            var adata          = new byte[0];
            var iv             = new byte[16];
            var salt           = new byte[8];

            _random.GetBytes(iv);
            _random.GetBytes(salt);
            var key = GenKeyBytes(password, salt, ks, iter);

            var nonSecretPayload = new byte[] { };

            var cipher     = new CcmBlockCipher(new AesFastEngine());
            var parameters = new CcmParameters(
                new KeyParameter(key), ts, iv.Take(13).ToArray(), nonSecretPayload);

            cipher.Init(true, parameters);

            var cipherText = new byte[cipher.GetOutputSize(plainTextBytes.Length)];
            var len        = cipher.ProcessBytes(plainTextBytes, 0, plainTextBytes.Length, cipherText, 0);

            cipher.DoFinal(cipherText, len);
            return(JsonConvert.SerializeObject(new SjclJson
            {
                IV = Convert.ToBase64String(iv),
                V = v,
                Iter = iter,
                KS = ks,
                TS = ts,
                Mode = "ccm",
                Cipher = "aes",
                AData = Convert.ToBase64String(adata),
                Salt = Convert.ToBase64String(salt),
                CT = Convert.ToBase64String(cipherText),
            }));
        }
コード例 #12
0
        public static string Encrypt(string password, string data)
        {
            RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();

            byte[] salt = new byte[8];
            rngCsp.GetBytes(salt);
            byte[] iv = new byte[16];
            rngCsp.GetBytes(iv);

            SJCLBlob ctdata = new SJCLBlob()
            {
                Mode       = "ccm",
                Cipher     = "aes",
                AuthData   = "",
                Iterations = 2000,
                KeySize    = 256,
                TagSize    = 64,
                Salt       = Convert.ToBase64String(salt),
                IV         = Convert.ToBase64String(iv),
                V          = 1
            };
            var key = DeriveKey(password, ctdata);

            byte[] rawdata = Encoding.UTF8.GetBytes(data);
            var    l       = FindIVLen(rawdata.Length);

            byte[] civ = new byte[l];
            Array.Copy((Array)iv, (Array)civ, (int)l);

            var ccmparams = new CcmParameters(key, ctdata.TagSize, civ, DecodeBase64(ctdata.AuthData));
            var ccmMode   = new CcmBlockCipher(new AesFastEngine());

            ccmMode.Init(true, ccmparams);
            var encBytes = new byte[ccmMode.GetOutputSize(rawdata.Length)];
            var res      = ccmMode.ProcessBytes(rawdata, 0, rawdata.Length, encBytes, 0);

            ccmMode.DoFinal(encBytes, res);
            ctdata.CipherText = Convert.ToBase64String(encBytes);

            return(JsonConvert.SerializeObject(ctdata));
        }
コード例 #13
0
        private void checkVectors(
            int count,
            CcmBlockCipher ccm,
            byte[] k,
            int macSize,
            byte[] n,
            byte[] a,
            byte[] p,
            byte[] t,
            byte[] c)
        {
            byte[] fa = new byte[a.Length / 2];
            byte[] la = new byte[a.Length - (a.Length / 2)];
            Array.Copy(a, 0, fa, 0, fa.Length);
            Array.Copy(a, fa.Length, la, 0, la.Length);

            checkVectors(count, ccm, "all initial associated data", k, macSize, n, a, null, p, t, c);
            checkVectors(count, ccm, "subsequent associated data", k, macSize, n, null, a, p, t, c);
            checkVectors(count, ccm, "split associated data", k, macSize, n, fa, la, p, t, c);
            //      checkVectors(count, ccm, "reuse key", null, macSize, n, fa, la, p, t, c);
        }
コード例 #14
0
        public string Encrypt(string data)
        {
            SecureRandom random = new SecureRandom();

            byte[] buffer = new byte[0x20];
            random.NextBytes(buffer);
            byte[] buffer2 = new byte[12];
            random.NextBytes(buffer2);
            byte[]         inArray    = this.rsaCipher.DoFinal(buffer);
            byte[]         bytes      = Encoding.UTF8.GetBytes(data);
            AeadParameters parameters = new AeadParameters(new KeyParameter(buffer), 0x40, buffer2, new byte[0]);

            this.aesCipher = new CcmBlockCipher(new AesFastEngine());
            this.aesCipher.Init(true, parameters);
            byte[] src = new byte[this.aesCipher.GetOutputSize(bytes.Length)];
            this.aesCipher.DoFinal(src, this.aesCipher.ProcessBytes(bytes, 0, bytes.Length, src, 0));
            byte[] dst = new byte[buffer2.Length + src.Length];
            Buffer.BlockCopy(buffer2, 0, dst, 0, buffer2.Length);
            Buffer.BlockCopy(src, 0, dst, buffer2.Length, src.Length);
            return("adyenc#0_1_15$" + Convert.ToBase64String(inArray) + "$" + Convert.ToBase64String(dst));
        }
コード例 #15
0
        public string Encrypt(string data)
        {
            SecureRandom random = new SecureRandom();

            // Generate 256-bits AES key
            byte[] aesKey = new byte[32];
            random.NextBytes(aesKey);

            // Generate Initialization Vector
            byte[] IV = new byte[12];
            random.NextBytes(IV);

            // Apply RSA/None/PKCS1Padding encryption to the AES key
            byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey);

            // Apply AES/CCM/NoPadding encryption to the data
            byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data);

            var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { });

            aesCipher = new CcmBlockCipher(new AesFastEngine());
            aesCipher.Init(true, ccmParameters);

            var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)];
            var res       = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0);

            aesCipher.DoFinal(encrypted, res);

            // Merge 'IV' and 'encrypted' to 'result'
            byte[] result = new byte[IV.Length + encrypted.Length];
            System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length);
            System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length);

            // Return encrypted data
            return(Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result));
        }
コード例 #16
0
        private void AES_CCM(byte[] k)
        {
            CcmBlockCipher cipher = new CcmBlockCipher(new AesEngine());
            KeyParameter   contentKey;
            int            cbitTag = 64;

            //  The requirements from JWA
            //  IV is 96 bits
            //  Authentication tag is 128 bits
            //  key sizes are 128, 192 and 256 bits

            _iv = new byte[96 / 8];
            s_PRNG.NextBytes(_iv);

            contentKey = new KeyParameter(k);

            //  Build the object to be hashed

            byte[] a = new byte[0];
            if (ProtectedMap != null)
            {
                a = Encoding.UTF8.GetBytes(ProtectedMap.ToString());
            }

            AeadParameters parameters = new AeadParameters(contentKey, 128, _iv, a);

            cipher.Init(true, parameters);

            byte[] c   = new byte[cipher.GetOutputSize(payload.Length)];
            int    len = cipher.ProcessBytes(payload, 0, payload.Length, c, 0);

            cipher.DoFinal(c, len);

            Array.Resize(ref c, c.Length - (128 / 8) + (cbitTag / 8));
            _RgbEncrypted = c;
        }
コード例 #17
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.");
        }
コード例 #18
0
        public override void PerformTest()
        {
            CcmBlockCipher ccm = new CcmBlockCipher(new AesEngine());

            checkVectors(0, ccm, K1, 32, N1, A1, P1, T1, C1);
            checkVectors(1, ccm, K2, 48, N2, A2, P2, T2, C2);
            checkVectors(2, ccm, K3, 64, N3, A3, P3, T3, C3);

            ivParamTest(0, ccm, K1, N1);

            //
            // 4 has a reduced associated text which needs to be replicated
            //
            byte[] a4 = new byte[65536];             // 524288 / 8

            for (int i = 0; i < a4.Length; i += A4.Length)
            {
                Array.Copy(A4, 0, a4, i, A4.Length);
            }

            checkVectors(3, ccm, K4, 112, N4, a4, P4, T4, C4);

            //
            // long data test
            //
            checkVectors(4, ccm, K4, 112, N4, A4, A4, T5, C5);

            // decryption with output specified, non-zero offset.
            ccm.Init(false, new AeadParameters(new KeyParameter(K2), 48, N2, A2));

            byte[] inBuf  = new byte[C2.Length + 10];
            byte[] outBuf = new byte[ccm.GetOutputSize(C2.Length) + 10];

            Array.Copy(C2, 0, inBuf, 10, C2.Length);

            int len = ccm.ProcessPacket(inBuf, 10, C2.Length, outBuf, 10);

            byte[] output = ccm.ProcessPacket(C2, 0, C2.Length);

            if (len != output.Length || !isEqual(output, outBuf, 10))
            {
                Fail("decryption output incorrect");
            }

            // encryption with output specified, non-zero offset.
            ccm.Init(true, new AeadParameters(new KeyParameter(K2), 48, N2, A2));

            int inLen = len;

            inBuf  = outBuf;
            outBuf = new byte[ccm.GetOutputSize(inLen) + 10];

            len    = ccm.ProcessPacket(inBuf, 10, inLen, outBuf, 10);
            output = ccm.ProcessPacket(inBuf, 10, inLen);

            if (len != output.Length || !isEqual(output, outBuf, 10))
            {
                Fail("encryption output incorrect");
            }

            //
            // exception tests
            //

            try
            {
                ccm.Init(false, new AeadParameters(new KeyParameter(K1), 32, N2, A2));

                ccm.ProcessPacket(C2, 0, C2.Length);

                Fail("invalid cipher text not picked up");
            }
            catch (InvalidCipherTextException)
            {
                // expected
            }

            try
            {
                ccm = new CcmBlockCipher(new DesEngine());

                Fail("incorrect block size not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                ccm.Init(false, new KeyParameter(K1));

                Fail("illegal argument not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
コード例 #19
0
        private void checkVectors(
            int count,
            CcmBlockCipher ccm,
            string additionalDataType,
            byte[] k,
            int macSize,
            byte[] n,
            byte[] a,
            byte[] sa,
            byte[] p,
            byte[] t,
            byte[] c)
        {
            KeyParameter keyParam = (k == null) ? null : new KeyParameter(k);

            ccm.Init(true, new AeadParameters(keyParam, macSize, n, a));

            byte[] enc = new byte[c.Length];

            if (sa != null)
            {
                ccm.ProcessAadBytes(sa, 0, sa.Length);
            }

            int len = ccm.ProcessBytes(p, 0, p.Length, enc, 0);

            len += ccm.DoFinal(enc, len);

//			ccm.Init(true, new AeadParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] enc = ccm.ProcessPacket(p, 0, p.Length);

            if (!AreEqual(c, enc))
            {
                Fail("encrypted stream fails to match in test " + count + " with " + additionalDataType);
            }

//			ccm.Init(false, new AeadParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] dec = ccm.ProcessPacket(enc, 0, enc.Length);

            ccm.Init(false, new AeadParameters(new KeyParameter(k), macSize, n, a));

            byte[] tmp = new byte[enc.Length];

            if (sa != null)
            {
                ccm.ProcessAadBytes(sa, 0, sa.Length);
            }

            len = ccm.ProcessBytes(enc, 0, enc.Length, tmp, 0);

            len += ccm.DoFinal(tmp, len);

            byte[] dec = new byte[len];

            Array.Copy(tmp, 0, dec, 0, len);

            if (!AreEqual(p, dec))
            {
                Fail("decrypted stream fails to match in test " + count + " with " + additionalDataType,
                     Hex.ToHexString(p), Hex.ToHexString(dec));
            }

            if (!AreEqual(t, ccm.GetMac()))
            {
                Fail("MAC fails to match in test " + count + " with " + additionalDataType);
            }
        }
コード例 #20
0
ファイル: CipherUtilities.cs プロジェクト: zyltntking/Lenneth
        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.");
        }
コード例 #21
0
ファイル: EncryptCommon.cs プロジェクト: jimsch/COSE-csharp
        private void AES_CCM_Decrypt(CBORObject alg, byte[] K)
        {
            CcmBlockCipher cipher = new CcmBlockCipher(new AesEngine());
            KeyParameter   ContentKey;
            int            cbitTag;
            int            cbIV;
            int            cbitKey;

            //  Figure out what the correct internal parameters to use are

            Debug.Assert(alg.Type == CBORType.Integer);
            switch ((AlgorithmValuesInt)alg.AsInt32())
            {
            case AlgorithmValuesInt.AES_CCM_16_64_128:
            case AlgorithmValuesInt.AES_CCM_64_64_128:
                cbitKey = 128;
                cbitTag = 64;
                break;

            case AlgorithmValuesInt.AES_CCM_16_128_128:
            case AlgorithmValuesInt.AES_CCM_64_128_128:
                cbitKey = 128;
                cbitTag = 128;
                break;

            case AlgorithmValuesInt.AES_CCM_16_64_256:
            case AlgorithmValuesInt.AES_CCM_64_64_256:
                cbitKey = 256;
                cbitTag = 64;
                break;

            case AlgorithmValuesInt.AES_CCM_16_128_256:
            case AlgorithmValuesInt.AES_CCM_64_128_256:
                cbitKey = 256;
                cbitTag = 128;
                break;

            default:
                throw new CoseException("Unsupported algorithm: " + alg);
            }

            switch ((AlgorithmValuesInt)alg.AsInt32())
            {
            case AlgorithmValuesInt.AES_CCM_16_64_128:
            case AlgorithmValuesInt.AES_CCM_16_64_256:
            case AlgorithmValuesInt.AES_CCM_16_128_128:
            case AlgorithmValuesInt.AES_CCM_16_128_256:
                cbIV = 15 - 2;
                break;

            case AlgorithmValuesInt.AES_CCM_64_64_128:
            case AlgorithmValuesInt.AES_CCM_64_64_256:
            case AlgorithmValuesInt.AES_CCM_64_128_256:
            case AlgorithmValuesInt.AES_CCM_64_128_128:
                cbIV = 15 - 8;
                break;

            default:
                throw new CoseException("Unsupported algorithm: " + alg);
            }

            //  The requirements from JWA

            byte[]     IV   = new byte[cbIV];
            CBORObject cbor = FindAttribute(HeaderKeys.IV);

            if (cbor != null)
            {
                if (cbor.Type != CBORType.ByteString)
                {
                    throw new CoseException("IV is incorrectly formed.");
                }
                if (cbor.GetByteString().Length > IV.Length)
                {
                    throw new CoseException("IV is too long.");
                }
                Array.Copy(cbor.GetByteString(), 0, IV, 0, IV.Length);
            }
            else
            {
                s_PRNG.NextBytes(IV);
                AddAttribute(HeaderKeys.IV, CBORObject.FromObject(IV), UNPROTECTED);
            }

            if (K == null)
            {
                throw new CoseException("Internal error");
            }
            if (K.Length != cbitKey / 8)
            {
                throw new CoseException("Incorrect key length");
            }

            ContentKey = new KeyParameter(K);

            //  Build the object to be hashed

            AeadParameters parameters = new AeadParameters(ContentKey, cbitTag, IV, getAADBytes());

            cipher.Init(false, parameters);
            byte[] C   = new byte[cipher.GetOutputSize(RgbEncrypted.Length)];
            int    len = cipher.ProcessBytes(RgbEncrypted, 0, RgbEncrypted.Length, C, 0);

            len += cipher.DoFinal(C, len);

            rgbContent = C;
        }
コード例 #22
0
        public override void PerformTest()
        {
            CcmBlockCipher ccm = new CcmBlockCipher(new AesEngine());

            checkVectors(0, ccm, K1, 32, N1, A1, P1, T1, C1);
            checkVectors(1, ccm, K2, 48, N2, A2, P2, T2, C2);
            checkVectors(2, ccm, K3, 64, N3, A3, P3, T3, C3);

            ivParamTest(0, ccm, K1, N1);

            //
            // 4 has a reduced associated text which needs to be replicated
            //
            byte[] a4 = new byte[65536];             // 524288 / 8

            for (int i = 0; i < a4.Length; i += A4.Length)
            {
                Array.Copy(A4, 0, a4, i, A4.Length);
            }

            checkVectors(3, ccm, K4, 112, N4, a4, P4, T4, C4);

            //
            // long data test
            //
            checkVectors(4, ccm, K4, 112, N4, A4, A4, T5, C5);

            //
            // exception tests
            //

            try
            {
                ccm.Init(false, new AeadParameters(new KeyParameter(K1), 32, N2, A2));

                ccm.ProcessPacket(C2, 0, C2.Length);

                Fail("invalid cipher text not picked up");
            }
            catch (InvalidCipherTextException)
            {
                // expected
            }

            try
            {
                ccm = new CcmBlockCipher(new DesEngine());

                Fail("incorrect block size not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                ccm.Init(false, new KeyParameter(K1));

                Fail("illegal argument not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
コード例 #23
0
        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.");
        }