/// <exception cref="ArgumentException">Wrong length of IV.</exception>
        public ICryptoTransform Create(CryptoDirection direction, Mode mode, byte[] iv)
        {
            if (iv.Length != BlockSize)
            {
                throw new ArgumentException("Wrong length of IV.");
            }

            InitRoundKey(direction);

            switch (mode)
            {
            default:
            case Mode.ECB:
                if (direction == CryptoDirection.Encrypt)
                {
                    return(new FROGEncryptTransform(_encryptRoundKeys));
                }
                else
                {
                    return(new FROGDecryptTransform(_decryptRoundKeys));
                }

            case Mode.CBC:
                return(CBC.Get(CreateNice(direction), iv, direction));

            case Mode.CFB:
                return(CFB.Get(CreateNice(CryptoDirection.Encrypt), iv, direction));

            case Mode.OFB:
                return(OFB.Get(CreateNice(CryptoDirection.Encrypt), iv, direction));
            }
        }
Пример #2
0
        private IMode ChooseMode(string mode, byte[] key, DesEngine engine)
        {
            IMode chosenMode;

            switch (mode)
            {
            case "ECB":
                chosenMode = new ECB(engine);
                break;

            case "CBC":
                chosenMode = new CBC(engine, key.ToArray());
                break;

            case "CFB":
                chosenMode = new CFB(engine, key.ToArray());
                break;

            case "OFB":
                chosenMode = new OFB(engine, key.ToArray());
                break;

            default:
                throw new Exception("Неправильный режим");
            }

            return(chosenMode);
        }
Пример #3
0
    /* executes class program */
    public static void Main(String[] args)
    {
        CFB cfb = new CFB();

        Console.Write("\n===== CFB (Cipher Feedback) =====\n");
        Console.Write("\n\n== START PROGRAM ==\n\n");
        cfb.driver();
        Console.Write("\n\n== END PROGRAM ==\n\n");
        Console.ReadLine();
    }
Пример #4
0
    public static void Main(String[] args)
    /* executes class program */
    {
        CFB cfb = new CFB();

        Console.Write("\n===== CFB (Cipher Feedback) =====\n");
        Console.Write("\n\n== START PROGRAM ==\n\n");
        cfb.driver();
        Console.Write("\n\n== END PROGRAM ==\n\n");
        Console.ReadLine();
    }
Пример #5
0
        private void CFBTest(byte[] Key, byte[, ][] Input, byte[, ][] Output)
        {
            byte[] outBytes = new byte[16];
            byte[] iv       = _vectors[0];
            int    index    = 12;

            if (Key.Length == 24)
            {
                index = 14;
            }
            else if (Key.Length == 32)
            {
                index = 16;
            }

            using (CFB mode1 = new CFB(new RHX()))
            {
                mode1.Initialize(true, new KeyParams(Key, iv));

                for (int i = 0; i < 4; i++)
                {
                    mode1.Transform(Input[index, i], 0, outBytes, 0);

                    if (Evaluate.AreEqual(outBytes, Output[index, i]) == false)
                    {
                        throw new Exception("CFB Mode: Encrypted arrays are not equal!");
                    }
                }
            }

            index++;

            using (CFB mode2 = new CFB(new RHX()))
            {
                mode2.Initialize(false, new KeyParams(Key, iv));

                for (int i = 0; i < 4; i++)
                {
                    mode2.Transform(Input[index, i], outBytes);

                    if (Evaluate.AreEqual(outBytes, _output[index, i]) == false)
                    {
                        throw new Exception("CFB Mode: Decrypted arrays are not equal!");
                    }
                }
            }
        }
        /// <exception cref="ArgumentException">Wrong key length or IV length</exception>
        public static ICryptoTransform Get(byte[] key, Size stateSize, byte[] IV, Mode mode, CryptoDirection direction)
        {
            switch (mode)
            {
            default:
            case Mode.ECB:
                return(Get(key, stateSize, direction));

            case Mode.CBC:
                return(CBC.Get(GetNice(key, stateSize, direction), IV, direction));

            case Mode.CFB:
                return(CFB.Get(GetNice(key, stateSize, CryptoDirection.Encrypt), IV, direction));

            case Mode.OFB:
                return(OFB.Get(GetNice(key, stateSize, CryptoDirection.Encrypt), IV, direction));
            }
        }
Пример #7
0
        private async void buttonEncode_Click(object sender, EventArgs e)
        {
            if ((textBoxKey.Text == "" && byteKey == null) ||
                (textBoxC0.Text == "" && bytec0 == null && !radioButtonECB.Checked))
            {
                MessageBox.Show("Не введены данные");
                return;
            }
            if (openFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            var  filePath = openFileDialog.FileName;
            Task read     = Task.Run(() =>
            {
                try
                {
                    text = File.ReadAllBytes(filePath);
                }
                catch (OutOfMemoryException ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            });

            read.Wait();

            if (text == null)
            {
                MessageBox.Show("Нет текста");
                return;
            }

            ICoder modeWork = null;

            if (byteKey == null)
            {
                byteKey = Encoding.Default.GetBytes(textBoxKey.Text);
            }

            var addByte = new List <byte>();

            for (int i = byteKey.Length; i < blockKeySize; i++)
            {
                addByte.Add(byteKey[i % byteKey.Length]);
            }
            byteKey = byteKey.Concat(addByte.ToArray()).ToArray();


            if (!radioButtonECB.Checked)
            {
                if (bytec0 == null)
                {
                    bytec0 = Encoding.Default.GetBytes(textBoxC0.Text);
                }
                addByte = new List <byte>();
                for (int i = bytec0.Length; i < blockSize; i++)
                {
                    addByte.Add(bytec0[i % bytec0.Length]);
                }
                bytec0 = bytec0.Concat(addByte.ToArray()).ToArray();
            }

            if (text.Length % blockSize != 0)
            {
                addByte = new List <byte>();
                for (int i = 0; i < blockSize - text.Length % blockSize; i++)
                {
                    addByte.Add(0);
                }

                text = text.Concat(addByte.ToArray()).ToArray();
            }
            uint[] T = new uint[14];

            for (int i = 0; i < byteKey.Length; i += subblockSize)
            {
                T[i / subblockSize] = BitConverter.ToUInt32(byteKey.Skip(i).Take(subblockSize).ToArray(), 0);
            }

            var      fileName = Path.GetFileName(openFileDialog.FileName);
            FormFile wind     = new FormFile(fileName, true);
            var      mars     = new Mars(T);

            if (radioButtonECB.Checked)
            {
                modeWork = new ECB(mars, wind);
            }
            else if (radioButtonCBC.Checked)
            {
                modeWork = new CBC(mars, bytec0, wind);
            }
            else if (radioButtonCFB.Checked)
            {
                modeWork = new CFB(mars, bytec0, wind);
            }
            else if (radioButtonOFB.Checked)
            {
                modeWork = new OFB(mars, bytec0, wind);
            }

            wind.Show();
            byte[] result = new byte[] { };
            if (radioButtonECB.Checked)
            {
                int             processorCount = 2;
                Task <byte[]>[] allTasks       = new Task <byte[]> [processorCount];

                for (int i = 0; i < processorCount; i++)
                {
                    int indexI = i; // т.к. значение i может поменяться при EndInvoke
                    allTasks[indexI] = Task.Run(() => modeWork.Encode(text.Skip(text.Length / processorCount * i).Take(text.Length / processorCount).ToArray()));
                    Thread.Sleep(100);
                }

                await Task.WhenAll(allTasks);

                for (int i = 0; i < processorCount; i++)
                {
                    result = result.Concat(allTasks[i].Result).ToArray();
                }
            }
            else
            {
                result = await modeWork.Encode(text);
            }
            wind.progressBar.Value = 100;

            using (var fs = System.IO.File.Create(Application.StartupPath + "\\(MARS)" + fileName))
            {
                await fs.WriteAsync(result, 0, result.Count());

                fs.Flush();
            }
        }
Пример #8
0
        public async Task <ActionResult <string> > Post(IFormFile message, KACD kacd)
        {
            byte[] byteMessage = null;

            if (message == null)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            ICoder modeWork = null;

            try
            {
                if (kacd.key == null || kacd.mode == null)
                {
                    throw new FormatException();
                }

                var byteKey = Encoding.Default.GetBytes(kacd.key);

                byte[] bytec0 = null;
                if (kacd.mode != "ecb")
                {
                    if (kacd.c0 == null)
                    {
                        throw new FormatException();
                    }
                    bytec0 = Encoding.Default.GetBytes(kacd.c0);
                    if (bytec0.Length != 8)
                    {
                        throw new FormatException();
                    }
                }

                if (byteKey.Length != 8)
                {
                    throw new FormatException();
                }

                using (var ms = new MemoryStream())
                {
                    message.CopyTo(ms);
                    byteMessage = ms.ToArray();
                }
                if (byteMessage.Length % 8 != 0)
                {
                    var addByte = new List <byte>();
                    for (int i = 0; i < 8 - byteMessage.Length % 8; i++)
                    {
                        addByte.Add(0);
                    }

                    byteMessage = byteMessage.Concat(addByte.ToArray()).ToArray();
                }


                var des = new DES(BitConverter.ToUInt64(byteKey));

                switch (kacd.mode)
                {
                case "ecb":
                    modeWork = new ECB(des);
                    break;

                case "cbc":
                    modeWork = new CBC(des, bytec0);
                    break;

                case "cfb":
                    modeWork = new CFB(des, bytec0);
                    break;

                case "ofb":
                    modeWork = new OFB(des, bytec0);
                    break;
                }
            }
            catch (FormatException)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            var result = kacd.decode != null?modeWork.Decode(byteMessage) : modeWork.Encode(byteMessage);

            var path = "(DES)" + message.FileName;

            using (var fs = System.IO.File.Create(_environment.WebRootPath + "/" + path))
            {
                fs.Write(result, 0, result.Count());
                fs.Flush();
            }

            return(path);
        }
Пример #9
0
        private void ParallelTest()
        {
            byte[]    data;
            byte[]    dec1;
            byte[]    dec2;
            byte[]    enc1;
            byte[]    enc2;
            int       blockSize;
            KeyParams keyParam = new KeyParams(new byte[32], new byte[16]);

            // CTR mode
            using (CTR cipher = new CTR(new RHX()))
            {
                data = GetBytes(1036);

                // how to calculate an ideal block size
                int plen = (data.Length / cipher.ParallelMinimumSize) * cipher.ParallelMinimumSize;
                // you can factor it up or down or use a default
                if (plen > cipher.ParallelMaximumSize)
                {
                    plen = 1024;
                }

                // set parallel block size
                cipher.ParallelBlockSize = plen;

                // parallel 1
                cipher.Initialize(true, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                enc1 = Transform2(cipher, data, blockSize);

                // linear 1
                cipher.Initialize(true, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                enc2 = Transform2(cipher, data, blockSize);

                if (Evaluate.AreEqual(enc1, enc2) == false)
                {
                    throw new Exception("Parallel CTR: Encrypted output is not equal!");
                }

                // encrypt //
                // parallel 2
                cipher.Initialize(true, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                enc1 = Transform1(cipher, data, blockSize);

                if (Evaluate.AreEqual(enc1, enc2) == false)
                {
                    throw new Exception("Parallel CTR: Encrypted output is not equal!");
                }

                // linear 2
                cipher.Initialize(true, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                enc2 = Transform2(cipher, data, blockSize);

                if (Evaluate.AreEqual(enc1, enc2) == false)
                {
                    throw new Exception("Parallel CTR: Encrypted output is not equal!");
                }

                // decrypt //
                // parallel 1
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec1 = Transform1(cipher, enc1, blockSize);

                // parallel 2
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec2 = Transform2(cipher, enc2, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CTR: Decrypted output is not equal!");
                }

                // linear 1
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform1(cipher, enc1, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CTR: Decrypted output is not equal!");
                }

                // linear 2
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform2(cipher, enc2, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CTR: Decrypted output is not equal!");
                }
            }

            if (Evaluate.AreEqual(data, dec1) == false)
            {
                throw new Exception("Parallel CTR: Decrypted output is not equal!");
            }
            if (Evaluate.AreEqual(data, dec2) == false)
            {
                throw new Exception("Parallel CTR: Decrypted output is not equal!");
            }

            OnProgress(new TestEventArgs("Passed Parallel CTR encryption and decryption tests.."));

            // CBC mode
            using (CBC cipher = new CBC(new RHX()))
            {
                // must be divisible by block size, add padding if required
                data = GetBytes(2048);

                // encrypt
                cipher.ParallelBlockSize = 1024;

                // t1: encrypt only in normal mode for cbc
                cipher.Initialize(true, keyParam);
                blockSize = cipher.BlockSize;
                enc1      = Transform1(cipher, data, blockSize);

                // t2
                cipher.Initialize(true, keyParam);
                blockSize = cipher.BlockSize;
                enc2      = Transform2(cipher, data, blockSize);

                if (Evaluate.AreEqual(enc1, enc2) == false)
                {
                    throw new Exception("Parallel CBC: Decrypted output is not equal!");
                }

                // decrypt //
                // t1 parallel
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec1 = Transform1(cipher, enc1, blockSize);

                // t1 linear
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform1(cipher, enc2, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CBC: Decrypted output is not equal!");
                }

                // t2 parallel
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec1 = Transform2(cipher, enc2, blockSize);

                // t2 linear
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform2(cipher, enc1, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CBC: Decrypted output is not equal!");
                }
            }

            if (Evaluate.AreEqual(dec1, data) == false)
            {
                throw new Exception("Parallel CBC: Decrypted output is not equal!");
            }
            if (Evaluate.AreEqual(dec2, data) == false)
            {
                throw new Exception("Parallel CBC: Decrypted output is not equal!");
            }

            OnProgress(new TestEventArgs("Passed Parallel CBC decryption tests.."));

            // CFB mode
            using (CFB cipher = new CFB(new RHX()))
            {
                // must be divisible by block size, add padding if required
                data = GetBytes(2048);

                // encrypt
                cipher.ParallelBlockSize = 1024;

                // t1: encrypt only in normal mode for cfb
                cipher.Initialize(true, keyParam);
                blockSize = cipher.BlockSize;
                enc1      = Transform1(cipher, data, blockSize);
                // t2
                cipher.Initialize(true, keyParam);
                blockSize = cipher.BlockSize;
                enc2      = Transform2(cipher, data, blockSize);

                if (Evaluate.AreEqual(enc1, enc2) == false)
                {
                    throw new Exception("Parallel CFB: Decrypted output is not equal!");
                }

                // decrypt //
                // t1 parallel
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec1 = Transform1(cipher, enc1, blockSize);

                // t1 linear
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform1(cipher, enc2, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CFB: Decrypted output is not equal!");
                }

                // t2 parallel
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = true;
                blockSize         = cipher.ParallelBlockSize;
                dec1 = Transform2(cipher, enc2, blockSize);

                // t2 linear
                cipher.Initialize(false, keyParam);
                cipher.IsParallel = false;
                blockSize         = cipher.BlockSize;
                dec2 = Transform2(cipher, enc1, blockSize);

                if (Evaluate.AreEqual(dec1, dec2) == false)
                {
                    throw new Exception("Parallel CFB: Decrypted output is not equal!");
                }
            }

            if (Evaluate.AreEqual(data, dec1) == false)
            {
                throw new Exception("Parallel CFB: Decrypted output is not equal!");
            }
            if (Evaluate.AreEqual(data, dec2) == false)
            {
                throw new Exception("Parallel CFB: Decrypted output is not equal!");
            }

            OnProgress(new TestEventArgs("Passed Parallel CFB decryption tests.."));

            // dispose container
            keyParam.Dispose();
        }
Пример #10
0
        private void CfbModeTest()
        {
            AllocateRandom(ref _iv, 16);
            AllocateRandom(ref _key, 32);

            KeyParams kp      = new KeyParams(_key, _iv);
            RHX       eng     = new RHX();
            CFB       cipher  = new CFB(eng);
            CFB       cipher2 = new CFB(eng);
            ISO7816   padding = new ISO7816();

            cipher.IsParallel = false;
            CipherStream cs = new CipherStream(cipher2, padding);

            for (int i = 0; i < 10; i++)
            {
                int sze      = AllocateRandom(ref _plnText, 0, eng.BlockSize);
                int prlBlock = sze - (sze % (cipher.BlockSize * _processorCount));
                _cmpText = new byte[sze];
                _decText = new byte[sze];
                _encText = new byte[sze];

                cipher.ParallelBlockSize  = prlBlock;
                cipher2.ParallelBlockSize = prlBlock;
                MemoryStream mIn  = new MemoryStream(_plnText);
                MemoryStream mOut = new MemoryStream();
                MemoryStream mRes = new MemoryStream();

                // *** Compare encryption output *** //

                // local processor
                cipher.Initialize(true, kp);
                BlockEncrypt(cipher, padding, _plnText, 0, ref _encText, 0);

                // streamcipher linear mode
                cs.IsParallel = false;
                // memorystream interface
                cs.Initialize(true, kp);
                cs.Write(mIn, mOut);

                if (!Evaluate.AreEqual(mOut.ToArray(), _encText))
                {
                    throw new Exception("CipherStreamTest: Encrypted arrays are not equal!");
                }

                // byte array interface
                cs.Initialize(true, kp);
                cs.Write(_plnText, 0, ref _cmpText, 0);

                if (!Evaluate.AreEqual(_cmpText, _encText))
                {
                    throw new Exception("CipherStreamTest: Encrypted arrays are not equal!");
                }

                // ***compare decryption output *** //

                // local processor
                cipher.Initialize(false, kp);
                BlockDecrypt(cipher, padding, _encText, 0, ref _decText, 0);

                if (!Evaluate.AreEqual(_plnText, _decText))
                {
                    throw new Exception("CipherStreamTest: Decrypted arrays are not equal!");
                }

                // decrypt linear mode
                cs.IsParallel = false;
                mOut.Seek(0, SeekOrigin.Begin);
                cs.Initialize(false, kp);
                cs.Write(mOut, mRes);

                if (!Evaluate.AreEqual(mRes.ToArray(), _decText))
                {
                    throw new Exception("CipherStreamTest: Decrypted arrays are not equal!");
                }

                // byte array interface
                cs.Initialize(false, kp);
                cs.Write(_encText, 0, ref _cmpText, 0);

                if (!Evaluate.AreEqual(_cmpText, _decText))
                {
                    throw new Exception("CipherStreamTest: Decrypted arrays are not equal!");
                }

                // decrypt parallel mode
                cs.IsParallel = true;
                mOut.Seek(0, SeekOrigin.Begin);
                mRes.Seek(0, SeekOrigin.Begin);
                cs.Initialize(false, kp);
                cs.Write(mOut, mRes);

                if (!Evaluate.AreEqual(mRes.ToArray(), _decText))
                {
                    throw new Exception("CipherStreamTest: Decrypted arrays are not equal!");
                }

                // byte array interface
                cs.Initialize(false, kp);
                Array.Resize(ref _cmpText, _encText.Length);
                cs.Write(_encText, 0, ref _cmpText, 0);

                if (!Evaluate.AreEqual(_cmpText, _decText))
                {
                    throw new Exception("CipherStreamTest: Decrypted arrays are not equal!");
                }
            }

            eng.Dispose();
        }