Exemplo n.º 1
0
        public void TestCorrect1()
        {
            OFB ofb    = createOFB(16, 16, 127);
            var actual = ofb.Decode(plaintext);

            CollectionAssert.AreEqual(expected, actual);
        }
        /// <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));
            }
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        public void TestCorrect3()
        {
            byte[] plain      = { 0x32 };
            byte[] ciphertext = { 0x54 };
            OFB    ofb        = createOFB(16, 16, 1);

            CollectionAssert.AreEqual(ciphertext, ofb.Decode(plain));
        }
Exemplo n.º 5
0
Arquivo: ofb.cs Projeto: Vsio/Virulife
    /* executes class program */
    public static void Main(String[] args)
    {
        OFB ofb = new OFB();

        Console.Write("\n===== OFB (Output Feedback) =====\n");
        Console.Write("\n\n== START PROGRAM ==\n\n");
        ofb.driver();
        Console.Write("\n\n== END PROGRAM ==\n\n");
        Console.ReadLine();
    }
Exemplo n.º 6
0
        public void TestCorrect2()
        {
            byte[] plain      = { 0x32, 0x88, 0x31, 0xe0, 0x43 };
            byte[] ciphertext = { 0x54, 0x67, 0xb9 };
            byte[] actual     = new byte[3];
            OFB    ofb        = createOFB(16, 16, 3);

            Array.Copy(ofb.Decode(plain), actual, 3);
            CollectionAssert.AreEqual(ciphertext, actual);
        }
Exemplo n.º 7
0
    public static void Main(String[] args)
    /* executes class program */
    {
        OFB ofb = new OFB();

        Console.Write("\n===== OFB (Output Feedback) =====\n");
        Console.Write("\n\n== START PROGRAM ==\n\n");
        ofb.driver();
        Console.Write("\n\n== END PROGRAM ==\n\n");
        Console.ReadLine();
    }
Exemplo n.º 8
0
        private void OFBTest(byte[] Key, byte[, ][] Input, byte[, ][] Output)
        {
            byte[] outBytes = new byte[16];
            byte[] iv       = _vectors[0];
            int    index    = 18;

            if (Key.Length == 24)
            {
                index = 20;
            }
            else if (Key.Length == 32)
            {
                index = 22;
            }

            using (OFB mode = new OFB(new RHX()))
            {
                mode.Initialize(true, new KeyParams(Key, iv));

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

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

            index++;

            using (OFB mode = new OFB(new RHX()))
            {
                mode.Initialize(false, new KeyParams(Key, iv));

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

                    if (Evaluate.AreEqual(outBytes, _output[index, i]) == false)
                    {
                        throw new Exception("OFB 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));
            }
        }
Exemplo n.º 10
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();
            }
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
 public void TestNotCorrectText()
 {
     OFB ofb    = createOFB(16, 16, 127);
     var actual = ofb.Decode(null);
 }
Exemplo n.º 13
0
        private void OfbModeTest()
        {
            AllocateRandom(ref _iv, 16);
            AllocateRandom(ref _key, 32);

            KeyParams kp      = new KeyParams(_key, _iv);
            RHX       eng     = new RHX();
            OFB       cipher  = new OFB(eng);
            OFB       cipher2 = new OFB(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];

                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
                cipher2.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);
                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();
        }