Example #1
0
        public void TestSeekSwap()
        {
            CStreamWriter writer = new CStreamWriter();

            writer.Write(LongData);

            CStreamReader reader = writer.CreateReader();

            byte[] buf = new byte[1024];

            // seek 5 bytes before EOF
            reader.Seek(LongData.Length - 5, SeekOrigin.Begin);

            // write more, ensure swap
            writer.Write(LongData);
            writer.Write(LongData);
            Assert.IsTrue(writer.IsSwapped);

            { // seek somewhere to the middle, read
                reader.Seek(LongData.Length * 2, SeekOrigin.Begin);
                int read = reader.Read(buf);
                Assert.AreEqual(buf.Length, read);
            }

            { // seek beyond length, assert still open, get EOF
                reader.Seek(LongData.Length * 3, SeekOrigin.Current);
                Assert.IsFalse(writer.IsClosed);
                int read = reader.Read(buf);
                Assert.AreEqual(0, read);
            }
        }
Example #2
0
        public void TestSwapWithReader()
        {
            CStreamWriter writer = new CStreamWriter();
            CStreamReader reader = writer.CreateReader();

            // write, not swapped
            writer.Write(LongData);
            Assert.IsFalse(writer.IsSwapped);

            // read a few bytes, but there are still a few bytes left
            byte[] buf = new byte[ShortData.Length];
            reader.Read(buf);
            Assert.IsTrue(reader.Position > 0);
            Assert.IsTrue(reader.Length > reader.Position);

            // fill buffer, assert swap
            writer.Write(LongData);
            writer.Write(LongData);
            Assert.IsTrue(writer.IsSwapped);
            Assert.IsTrue(reader.IsSwapped);

            // try to read more than available, receive less
            buf = new byte[writer.Length * 2];
            int read = reader.Read(buf);

            Assert.IsTrue(read < buf.Length);

            // close writer, assert EOF
            writer.Close();
            int result = reader.ReadByte();

            Assert.AreEqual(-1, result);
        }
Example #3
0
        public void Execute()
        {
            if (InputStreamOne == null || InputStreamTwo == null)
            {
                return;
            }

            using (CStreamReader reader1 = InputStreamOne.CreateReader(), reader2 = InputStreamTwo.CreateReader())
            {
                outputStreamWriter = new CStreamWriter();
                EventsHelper.PropertyChanged(PropertyChanged, this, "OutputStream");

                int    bytesRead;
                byte[] buffer = new byte[1024];

                // Input One
                while ((bytesRead = reader1.Read(buffer)) > 0)
                {
                    outputStreamWriter.Write(buffer, 0, bytesRead);
                }
                // Input Two
                while ((bytesRead = reader2.Read(buffer)) > 0)
                {
                    outputStreamWriter.Write(buffer, 0, bytesRead);
                }

                outputStreamWriter.Close();
            }
        }
Example #4
0
        public void TestDestructorWithReader()
        {
            CStreamWriter writer = new CStreamWriter();

            // write, not swapped
            writer.Write(LongData);

            // read something and assert there's more
            CStreamReader reader = writer.CreateReader();

            byte[] buf = new byte[ShortData.Length];
            reader.Read(buf);
            Assert.IsTrue(reader.Position > 0);
            Assert.IsTrue(reader.Length > reader.Position);
            Assert.IsFalse(reader.IsSwapped);

            // write more, assert swap
            writer.Write(LongData);
            writer.Write(LongData);
            Assert.IsTrue(reader.IsSwapped);

            string filePath = writer.FilePath;

            // destroy ref to writer
            writer.Close();
            writer = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.IsNull(writer);

            // assert reading still works
            Assert.IsTrue(File.Exists(filePath));
            Assert.IsNotNull(reader);
            int sum = 0;

            while (sum < LongData.Length * 2)
            {
                int read = reader.Read(buf);
                Assert.IsTrue(read > 0);
                sum += read;
            }

            // destroy reader
            reader = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            // deleted tempfile
            Assert.IsFalse(File.Exists(filePath));
        }
Example #5
0
        public void TestExhaustiveRead()
        {
            CStreamWriter writer = new CStreamWriter();

            writer.Write(LongData);
            writer.Write(LongData);
            writer.Write(LongData);
            writer.Close();

            CStreamReader reader = writer.CreateReader();

            byte[] bigbuf = reader.ReadFully();

            Assert.AreEqual(LongData.Length * 3, bigbuf.Length);
        }
Example #6
0
        public void TestSeek()
        {
            CStreamWriter writer = new CStreamWriter();

            writer.Write(LongData);
            writer.Close();

            CStreamReader reader = writer.CreateReader();

            byte[] buf = new byte[1024];

            { // seek 5 bytes before EOF, attempt to read much, get 5 bytes
                reader.Seek(LongData.Length - 5, SeekOrigin.Begin);
                int read = reader.Read(buf, 0, int.MaxValue);
                Assert.AreEqual(5, read);
            }

            { // read EOF
                int read = reader.Read(buf, 0, int.MaxValue);
                Assert.AreEqual(0, read);
            }

            { // seek beyond stream length, read EOF
                reader.Seek(LongData.Length * 3, SeekOrigin.Begin);
                int read = reader.Read(buf, 0, int.MaxValue);
                Assert.AreEqual(0, read);
            }

            { // seek back, read again
                reader.Seek(LongData.Length - 5, SeekOrigin.Begin);
                int read = reader.Read(buf, 0, int.MaxValue);
                Assert.AreEqual(5, read);
            }
        }
Example #7
0
        public void TestReader()
        {
            CStreamWriter writer = new CStreamWriter();

            // put 6 bytes
            writer.Write(ShortData);
            CStreamReader reader = writer.CreateReader();

            // length==6, position==0
            Assert.AreEqual(0, reader.Position);
            Assert.AreEqual(ShortData.Length, reader.Length);

            // try to read more bytes than available
            byte[] buf = new byte[ShortData.Length * 1000];
            Assert.AreNotEqual(buf.Length, ShortData.Length);
            Assert.IsFalse(buf.SequenceEqual(ShortData));
            int read = reader.Read(buf);

            Assert.AreEqual(ShortData.Length, read);

            // assert the first few bytes are still correct
            byte[] buf2 = new byte[ShortData.Length];
            Array.Copy(buf, buf2, buf2.Length);
            Assert.IsTrue(buf2.SequenceEqual(ShortData));

            // not swapped
            Assert.IsFalse(reader.IsSwapped);
        }
Example #8
0
        void OnPacketArrival(object sender, CaptureEventArgs e)
        {
            GuiLogMessage("Packet: " + e.ToString(), NotificationLevel.Debug);

            if (writer != null && !writer.IsClosed)
            {
                writer.Write(e.Packet.Data);
            }

            this.DataPacket = e.Packet.Data;
            OnPropertyChanged("DataPacket");
        }
Example #9
0
        public void TestDestructor()
        {
            CStreamWriter writer = new CStreamWriter();

            Assert.IsFalse(writer.IsSwapped);
            writer.Write(LongData);
            Assert.IsFalse(writer.IsSwapped);
            writer.Write(LongData);

            Assert.IsTrue(writer.IsSwapped);

            string filePath = writer.FilePath;

            Assert.IsTrue(File.Exists(filePath));

            // force GC
            writer = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // tempfile deleted
            Assert.IsFalse(File.Exists(filePath));
        }
Example #10
0
        public void TestWriter()
        {
            CStreamWriter writer = new CStreamWriter();

            // put 6 bytes
            writer.Write(ShortData);

            // length == position == 6
            Assert.AreEqual(ShortData.Length, writer.Length);
            Assert.AreEqual(ShortData.Length, writer.Position);

            // not swapped
            Assert.IsFalse(writer.IsSwapped);
        }
Example #11
0
        public void Execute()
        {
            if (amountOfNumbers <= 0)
            {
                GuiLogMessage("Negative amount of numbers cant be generated", NotificationLevel.Warning);
                ProgressChanged(1, 1);
                return;
            }

            if (hasSeed)
            {
                setSeed(seed);
            }

            ProgressChanged(0, 1);

            CStreamWriter writer = new CStreamWriter();

            data = writer;
            uint current;

            byte[] nextData;
            outputNumbers = new BigInteger[amountOfNumbers];

            for (int i = 0; i < amountOfNumbers; i++)
            {
                // nothing to say here, it is simple writing the necessary amount of uints onto the stream
                current          = getNextUInt();
                outputNumbers[i] = current;
                nextData         = BitConverter.GetBytes(current);
                if (littleEndian)
                {
                    Array.Reverse(nextData);
                }
                writer.Write(nextData);
                ProgressChanged(i, amountOfNumbers);
            }
            writer.Close();

            OnPropertyChanged("OutputData");
            OnPropertyChanged("OutputNumbers");
            GuiLogMessage("Generation finished", NotificationLevel.Debug);

            ProgressChanged(1, 1);
        }
Example #12
0
        private void UpdateOutputs(byte[] data, int connectionID)
        {
            using (var streamWriter = new CStreamWriter())
            {
                PackageStream = streamWriter;
                streamWriter.Write(data);
                streamWriter.Close();
            }
            OnPropertyChanged("PackageStream");

            if (returnLastPackage) //change single output if no item is selected
            {
                SingleOutput = data;
                OnPropertyChanged("SingleOutput");
            }

            ConnectionIDOutput = connectionID;
            OnPropertyChanged("ConnectionIDOutput");
        }
Example #13
0
        public void TestSwap()
        {
            CStreamWriter writer = new CStreamWriter();

            // fill buffer with Length-1 bytes
            writer.Write(LongData);
            Assert.AreEqual(LongData.Length, writer.Position);
            Assert.IsFalse(writer.IsSwapped);

            // fill last byte
            writer.WriteByte(5);
            Assert.AreEqual(LongData.Length + 1, writer.Position);
            Assert.IsFalse(writer.IsSwapped);

            // write one byte more, assert swap
            writer.WriteByte(10);
            Assert.AreEqual(LongData.Length + 2, writer.Position);
            Assert.IsTrue(writer.IsSwapped);
        }
Example #14
0
        private void ReadProcessOutput(object sendingProcess, DataReceivedEventArgs data)
        {
            //Debug.WriteLine("ReadProcessOutput event fired at {0}", System.DateTime.UtcNow);
            switch (settings.SatString)
            {
            case SATSolverSettings.Solver.MiniSAT:
            {
                if (!(data.Data == null))
                {
                    string str = data.Data.ToString();
                    if (str.Contains("WARNING!"))
                    {
                        GuiLogMessage(data.Data.ToString(), NotificationLevel.Warning);
                    }
                    else
                    {
                        if (str.Contains("Parse time"))
                        {
                            ProgressChanged(5, 100);
                        }
                        else if (str.Contains("Simplification time"))
                        {
                            ProgressChanged(10, 100);
                        }
                        else if (str.Contains("restarts"))
                        {
                            ProgressChanged(99, 100);
                        }
                        outputConsoleString.AppendLine(data.Data.ToString());
                        outputConsoleStream = new CStreamWriter();
                        outputConsoleStream.Write(encoding.GetBytes(outputConsoleString.ToString()));
                        outputConsoleStream.Close();
                        OnPropertyChanged("OutputConsoleStream");
                    }
                }
                break;
            }

            default: break;
            }
        }
Example #15
0
        void exitcodeHandling(int exitcode)
        {
            switch (settings.SatString)
            {
            case SATSolverSettings.Solver.MiniSAT:
            {
                switch (exitcode)
                {
                case 1:
                {
                    GuiLogMessage("ERROR: Could not open file", NotificationLevel.Error);
                    break;
                }

                case 2:
                {
                    GuiLogMessage("INTERRUPTED", NotificationLevel.Info);
                    break;
                }

                case 3:
                {
                    GuiLogMessage("PARSE ERROR: Unexpected char in cnf (Maybe a clause is not terminated by '0'?)", NotificationLevel.Error);
                    break;
                }

                case 4:
                {
                    GuiLogMessage("INDETERMINATE ERROR! (Maybe out of memory?)", NotificationLevel.Error);
                    break;
                }

                case 5:
                {
                    GuiLogMessage("ERROR: Invalid Option", NotificationLevel.Error);
                    break;
                }

                case 10: goto case 20;             // case 10: UNSAT, case 20: SAT

                case 20:
                {
                    string line;
                    //while ((line = reader.ReadLine()) != null)
                    //{
                    //    line += "\n";
                    //    outputConsoleStream.Write(encoding.GetBytes(line));
                    //}
                    //reader.Close();

                    using (reader = new StreamReader(outputResultFilename))
                    {
                        while ((line = reader.ReadLine()) != null)
                        {
                            line += "\n";
                            outputResultStream.Write(encoding.GetBytes(line));
                        }
                    }
                    break;
                }

                //case 30: // print usage help
                //    {
                //        string line;
                //        while ((line = errorReader.ReadLine()) != null)
                //        {
                //            line += "\n";
                //            outputConsoleStream.Write(encoding.GetBytes(line));
                //        }
                //        errorReader.Close();
                //        break;
                //    }
                case 40: goto case 20;             // print dimacs (output preprocessed cnf)

                default:
                {
                    GuiLogMessage("Exitcode " + exitcode, NotificationLevel.Debug);
                    break;
                }
                }
                break;
            }

            default: break;
            }
        }
Example #16
0
        private void Crypt()
        {
            try
            {
                ICryptoTransform   p_encryptor;
                SymmetricAlgorithm p_alg = TwofishManaged.Create();

                ConfigureAlg(p_alg);

                outputStreamWriter = new CStreamWriter();
                ICryptoolStream inputdata = InputStream;

                if (settings.Action == 0)
                {
                    inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                }

                CStreamReader reader = inputdata.CreateReader();

                byte[] tmpInput   = BlockCipherHelper.StreamToByteArray(inputdata);
                byte[] outputData = new byte[tmpInput.Length];
                byte[] IV         = new byte[p_alg.IV.Length];
                Array.Copy(p_alg.IV, IV, p_alg.IV.Length);
                int bs = p_alg.BlockSize >> 3;

                if (settings.Mode == 0) // ECB
                {
                    p_encryptor = (settings.Action == 0) ? p_alg.CreateEncryptor(p_alg.Key, p_alg.IV) : p_alg.CreateDecryptor(p_alg.Key, p_alg.IV);
                    for (int pos = 0; pos < tmpInput.Length; pos += bs)
                    {
                        p_encryptor.TransformBlock(tmpInput, pos, bs, outputData, pos);
                    }
                }
                else if (settings.Mode == 1) // CBC
                {
                    if (settings.Action == 0)
                    {
                        p_encryptor = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);
                        for (int pos = 0; pos < tmpInput.Length; pos += bs)
                        {
                            for (int i = 0; i < bs; i++)
                            {
                                tmpInput[pos + i] ^= IV[i];
                            }
                            p_encryptor.TransformBlock(tmpInput, pos, bs, outputData, pos);
                            for (int i = 0; i < bs; i++)
                            {
                                IV[i] = outputData[pos + i];
                            }
                        }
                    }
                    else
                    {
                        p_encryptor = p_alg.CreateDecryptor(p_alg.Key, p_alg.IV);
                        for (int pos = 0; pos < tmpInput.Length; pos += bs)
                        {
                            p_encryptor.TransformBlock(tmpInput, pos, bs, outputData, pos);
                            for (int i = 0; i < bs; i++)
                            {
                                outputData[pos + i] ^= IV[i];
                                IV[i] = tmpInput[pos + i];
                            }
                        }
                    }
                }
                else if (settings.Mode == 2) // CFB
                {
                    p_encryptor = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);
                    if (settings.Action == 0)
                    {
                        for (int pos = 0; pos < tmpInput.Length; pos += bs)
                        {
                            p_encryptor.TransformBlock(IV, 0, p_encryptor.InputBlockSize, outputData, pos);
                            for (int i = 0; i < bs; i++)
                            {
                                outputData[pos + i] ^= tmpInput[pos + i];
                                IV[i] = outputData[pos + i];
                            }
                        }
                    }
                    else
                    {
                        for (int pos = 0; pos < tmpInput.Length; pos += bs)
                        {
                            p_encryptor.TransformBlock(IV, 0, p_encryptor.InputBlockSize, outputData, pos);
                            for (int i = 0; i < bs; i++)
                            {
                                IV[i] = tmpInput[pos + i];
                                outputData[pos + i] ^= tmpInput[pos + i];
                            }
                        }
                    }
                }
                else if (settings.Mode == 3) // OFB
                {
                    p_encryptor = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);
                    for (int pos = 0; pos < tmpInput.Length; pos += bs)
                    {
                        p_encryptor.TransformBlock(IV, 0, p_encryptor.InputBlockSize, outputData, pos);
                        for (int i = 0; i < bs; i++)
                        {
                            IV[i] = outputData[pos + i];
                            outputData[pos + i] ^= tmpInput[pos + i];
                        }
                    }
                }

                outputStreamWriter.Write(outputData);

                //if( p_encryptor!=null ) p_encryptor.Dispose();
                outputStreamWriter.Close();

                if (settings.Action == 1)
                {
                    outputStreamWriter = BlockCipherHelper.StripPadding(outputStreamWriter, settings.padmap[settings.Padding], p_alg.BlockSize / 8) as CStreamWriter;
                }

                OnPropertyChanged("OutputStream");
            }
            catch (CryptographicException cryptographicException)
            {
                // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
                // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                // the error messages will be doubled.
                // As a workaround we set p_crypto_stream to null here.
                p_crypto_stream = null;
                GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
        }
Example #17
0
        public void Execute()
        {
            if (inputStream == null || inputStream.Length == 0)
            {
                return;
            }

            try
            {
                internalInputByteList = new List <byte[]>();
                using (CStreamReader reader = inputStream.CreateReader())
                {
                    reader.WaitEof(); // does not support chunked streaming

                    /// Checks if the input stream contains a valid value. If not, class waits for input AND DOES NOTHING.
                    /// XXX: Execute() does not stop. Bug?
                    loadList(reader);

                    //GuiLogMessage("Ich habe jetzt " + internalInputByteList.Count + " Pakete....", NotificationLevel.Warning);
                    // Is there a key? - If yes, go on. If no: Give out a warning!
                    switch (checkForValidKey())
                    {
                    // Key is valid, so do nothing.
                    case 0:
                        break;

                    // Key is null reference or of length 0
                    case 1:
                        // Warning to the outside world and exit.
                        GuiLogMessage("WARNING - No key provided. Aborting now.", NotificationLevel.Error);
                        return;

                    // Key is of wrong size. Warning and create a dummey key.
                    case 2:
                        GuiLogMessage("WARNING -- wrong key size. Must be 5 or 13 bytes.", NotificationLevel.Error);
                        return;

                    default:
                        break;
                    }
                    outputStreamWriter = new CStreamWriter();
                    outputStreamWriter.Write(header, 0, header.Length);
                    key = new byte[inputByteKey.Length + 3];
                    for (int i = 0; i < inputByteKey.Length; i++)
                    {
                        key[i + 3] = inputByteKey[i];
                    }
                    counter = 0;
                    byte[] packetIndividualHeader = new byte[16];
                    packetIndividualHeader[0] = 0x0D;
                    packetIndividualHeader[1] = 0x12;
                    packetIndividualHeader[2] = 0xC9;
                    packetIndividualHeader[3] = 0x48;
                    packetIndividualHeader[4] = 0x78;
                    packetIndividualHeader[5] = 0x70;
                    packetIndividualHeader[6] = 0x01;
                    packetIndividualHeader[7] = 0x00;
                    // size of sniffed packet, used for looking in packet with Wireshark
                    packetIndividualHeader[8]  = 0x00;
                    packetIndividualHeader[9]  = 0x00;
                    packetIndividualHeader[10] = 0x00;
                    packetIndividualHeader[11] = 0x00;
                    // size
                    packetIndividualHeader[12] = 0x00;
                    packetIndividualHeader[13] = 0x00;
                    packetIndividualHeader[14] = 0x00;
                    packetIndividualHeader[15] = 0x00;

                    DateTime startTime = DateTime.Now;
                    for (int j = 0; j < internalInputByteList.Count; j++)
                    {
                        if (stop)
                        {
                            break;
                        }
                        byte[] tempInputByte = internalInputByteList.ElementAt(j);
                        lengthOfInputByte  = tempInputByte.Length;
                        lengthOfOutputByte = lengthOfInputByte;
                        // Dependeing on action, there are some modifications to the packet necessary. That's done here.
                        switch (settings.Action)
                        {
                        case 0:
                            tempInputByte     = concatenateTwoArrays(createLLCAndSNAPHeader(), tempInputByte);
                            lengthOfInputByte = lengthOfOutputByte = tempInputByte.Length;

                            crc32 = new CRC32();
                            byte[] icv = crc32.ComputeHash(tempInputByte);

                            lengthOfInputByte  += 4;
                            lengthOfOutputByte += 4;

                            Array.Resize(ref tempInputByte, lengthOfInputByte);
                            tempInputByte[lengthOfInputByte - 4] = icv[0];
                            tempInputByte[lengthOfInputByte - 3] = icv[1];
                            tempInputByte[lengthOfInputByte - 2] = icv[2];
                            tempInputByte[lengthOfInputByte - 1] = icv[3];

                            byte[] size = get4BytesFromInt(lengthOfInputByte + 28);
                            packetIndividualHeader[8]  = size[0];
                            packetIndividualHeader[9]  = size[1];
                            packetIndividualHeader[10] = size[2];
                            packetIndividualHeader[11] = size[3];

                            packetIndividualHeader[12] = size[0];
                            packetIndividualHeader[13] = size[1];
                            packetIndividualHeader[14] = size[2];
                            packetIndividualHeader[15] = size[3];

                            //permutation = new byte[256];
                            getInitialisationVector();
                            //outputByte = new byte[lengthOfOutputByte];
                            key[0] = iV[0];
                            key[1] = iV[1];
                            key[2] = iV[2];

                            outputByte = RC4.rc4encrypt(tempInputByte, key);

                            // Key index
                            outputByte = concatenateTwoArrays(new byte[] { 0x00 }, outputByte);
                            // initialisation vector
                            outputByte = concatenateTwoArrays(iV, outputByte);
                            // sequence controll
                            outputByte = concatenateTwoArrays(new byte[] { 0xA5 }, outputByte);
                            // Frame number
                            outputByte = concatenateTwoArrays(new byte[] { 0xC0 }, outputByte);
                            // MAC address destination
                            outputByte = concatenateTwoArrays(new byte[] { 0x00, 0x12, 0xBF, 0xDC, 0x4E, 0x7A }, outputByte);
                            // MAC address source
                            outputByte = concatenateTwoArrays(new byte[] { 0x00, 0xA0, 0xD1, 0x25, 0xB9, 0xEC }, outputByte);
                            // BSS ID
                            outputByte = concatenateTwoArrays(new byte[] { 0x00, 0x12, 0xBF, 0xDC, 0x4E, 0x7C }, outputByte);
                            // IEEE 802.11 header
                            outputByte = concatenateTwoArrays(new byte[] { 0x08, 0x41, 0x75, 0x00 }, outputByte);
                            // packet individual header, size and some other information
                            outputByte = concatenateTwoArrays(packetIndividualHeader, outputByte);
                            //outputByteList.Add(outputByte);
                            outputStreamWriter.Write(outputByte, 0, outputByte.Length);

                            crc32 = null;
                            icv   = null;
                            size  = null;
                            //permutation = null;
                            tempInputByte = null;
                            outputByte    = null;
                            break;

                        case 1:
                            byte[] pIH = providePacketIndividualHeader(tempInputByte);
                            tempInputByte = removePacketIndividualHeader(tempInputByte);

                            byte[] iEEEHeaderInformation = provideFirst28Bytes(tempInputByte);
                            tempInputByte = removeFirst28Bytes(tempInputByte);

                            key[0] = iEEEHeaderInformation[24];
                            key[1] = iEEEHeaderInformation[25];
                            key[2] = iEEEHeaderInformation[26];


                            iEEEHeaderInformation = removeWEPParameters(iEEEHeaderInformation);

                            lengthOfInputByte = lengthOfOutputByte = tempInputByte.Length;

                            // new packet size = packetsize + 28 (=IEEE header) - WEP parameters (IV & key index, 4 bytes) - ICV (4 bytes)
                            byte[] sizeCase1 = get4BytesFromInt(lengthOfOutputByte + 20);
                            pIH[8]  = sizeCase1[0];
                            pIH[9]  = sizeCase1[1];
                            pIH[10] = sizeCase1[2];
                            pIH[11] = sizeCase1[3];

                            pIH[12] = sizeCase1[0];
                            pIH[13] = sizeCase1[1];
                            pIH[14] = sizeCase1[2];
                            pIH[15] = sizeCase1[3];

                            outputByte = RC4.rc4encrypt(tempInputByte, key);

                            outputByte = removeICV(tempInputByte);

                            // IEEE header and output byte are concatenated
                            outputByte = concatenateTwoArrays(iEEEHeaderInformation, outputByte);

                            // packet individual header, size and some other information
                            outputByte = concatenateTwoArrays(pIH, outputByte);
                            //outputByteList.Add(outputByte);
                            outputStreamWriter.Write(outputByte, 0, outputByte.Length);

                            outputByte            = null;
                            pIH                   = null;
                            iEEEHeaderInformation = null;
                            size                  = null;
                            break;

                        default:
                            break;
                        }
                        counter++;
                        if (this.internalInputByteList != null)
                        {
                            ProgressChanged(counter, internalInputByteList.Count);
                        }
                        tempInputByte = null;
                    }
                    DateTime stopTime = DateTime.Now;
                    TimeSpan duration = stopTime - startTime;
                    if (!stop)
                    {
                        if (settings.Action == 0)
                        {
                            GuiLogMessage("Encryption complete!", NotificationLevel.Info);
                        }
                        if (settings.Action == 1)
                        {
                            GuiLogMessage("Decryption complete!", NotificationLevel.Info);
                        }
                        if (counter == 1)
                        {
                            GuiLogMessage("Time used [h:min:sec]: " + duration.ToString(), NotificationLevel.Info);
                        }
                        else
                        {
                            GuiLogMessage("Time used [h:min:sec]: " + duration.ToString() + " for " + counter.ToString("#,#", CultureInfo.InstalledUICulture) + " packets.", NotificationLevel.Info);
                        }
                        outputStreamWriter.Close();
                        OnPropertyChanged("OutputStream");
                    }
                    if (stop)
                    {
                        outputStreamWriter.Close();
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                    internalInputByteList.Clear();
                    internalInputByteList = null;
                    key = null;
                }
            }
            catch (Exception exc)
            {
                GuiLogMessage(exc.Message.ToString(), NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1.0, 1.0);
            }
        }
Example #18
0
        public void Execute()
        {
            /* do not execute if checks in PreExecution() failed */
            if (!execute)
            {
                return;
            }

            ProgressChanged(0, 1);

            byte[] input, output;
            int    outputLength, rate, capacity;

            /* setup output stream writer */
            CStreamWriter OutputStreamwriter = new CStreamWriter();

            OutputStream = OutputStreamwriter;
            OnPropertyChanged("OutputStream");

            #if _DEBUG_
            /* setup debug stream writer */
            TextWriter    consoleOut        = Console.Out; // save the standard output
            CStreamWriter debugStream       = new CStreamWriter();
            StreamWriter  debugStreamWriter = new StreamWriter(debugStream);
            debugStreamWriter.AutoFlush = true;     // flush stream every time WriteLine is called
            Console.SetOut(debugStreamWriter);
            DebugStream = debugStream;
            OnPropertyChanged("DebugStream");
            #endif

            #region get input

            /* read input */
            using (CStreamReader reader = InputStream.CreateReader())
            {
                int    bytesRead;
                byte[] buffer = new byte[128];      // buffer of length 128 byte

                MemoryStream stream = new MemoryStream();
                BinaryWriter bw     = new BinaryWriter(stream);

                while ((bytesRead = reader.Read(buffer)) > 0)
                {
                    bw.Write(buffer, 0, bytesRead);
                }

                bw.Close();
                input = stream.ToArray();
                OnPropertyChanged("OutputStream");
            }

            #endregion

            outputLength = settings.OutputLength;
            rate         = settings.Rate;
            capacity     = settings.Capacity;

            /* show presentation intro */
            #region presentation intro

            if (pres.IsVisible)
            {
                /* clean up last round */
                pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                {
                    pres.absorbGrid.Visibility                            = Visibility.Hidden;
                    pres.imgBlankPage.Visibility                          = Visibility.Hidden;
                    pres.labelOutput.Visibility                           = Visibility.Hidden;
                    pres.textBlockStateBeforeAbsorb.Text                  = "";
                    pres.textBlockBlockToAbsorb.Text                      = "";
                    pres.textBlockStateAfterAbsorb.Text                   = "";
                    pres.labelCurrentPhase.Content                        = "";
                    pres.labelCurrentStep.Content                         = "";
                    pres.textBlockExplanation.Text                        = "";
                    pres.textBlockParametersNotSupported.Visibility       = Visibility.Hidden;
                    pres.textBlockParametersNotSupported.Text             = "";
                    pres.textBlockStepPresentationNotAvailable.Visibility = Visibility.Hidden;
                    pres.textBlockStepPresentationNotAvailable.Text       = "";

                    pres.buttonNext.IsEnabled            = true;
                    pres.buttonSkip.IsEnabled            = false;
                    pres.buttonAutostep.IsEnabled        = false;
                    pres.buttonSkipPermutation.IsEnabled = false;
                    pres.autostepSpeedSlider.IsEnabled   = false;
                    pres.spButtons.Visibility            = Visibility.Visible;
                    pres.buttonSkipIntro.Visibility      = Visibility.Visible;

                    pres.imgIntroFirstPage.Visibility = Visibility.Visible;
                }, null);

                AutoResetEvent buttonNextClickedEvent = pres.buttonNextClickedEvent;

                #region check if selected parameters are supported
                if (outputLength > rate)
                {
                    pres.skipPresentation = true;

                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.imgIntroFirstPage.Visibility = Visibility.Hidden;

                        pres.textBlockParametersNotSupported.Text       = Resources.PresOutputLengthError;
                        pres.textBlockParametersNotSupported.Visibility = Visibility.Visible;
                    }, null);
                }
                else if (rate + capacity < 200)
                {
                    pres.skipPresentation = true;

                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.imgIntroFirstPage.Visibility = Visibility.Hidden;

                        pres.textBlockParametersNotSupported.Text       = Resources.PresStateSizeError;
                        pres.textBlockParametersNotSupported.Visibility = Visibility.Visible;
                    }, null);
                }
                #endregion

                if (!pres.skipPresentation)
                {
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.imgIntroFirstPage.Visibility      = Visibility.Hidden;
                        pres.labelIntroIntroduction.Visibility = Visibility.Visible;
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelCurrentPhase.Content = Resources.PresIntroduction;
                        pres.labelCurrentStep.Content  = Resources.PresInitialization;

                        pres.textBlockIntroduction.Text = string.Format(Resources.PresInitializationText, (rate + capacity), capacity, rate);

                        pres.labelIntroIntroduction.Visibility = Visibility.Hidden;
                        pres.imgIntroSpongeInit.Visibility     = Visibility.Visible;
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelCurrentStep.Content = Resources.PresAbsorbingPhase;

                        pres.textBlockIntroduction.Text =
                            string.Format(Resources.PresAbsorbingPhaseText, rate);

                        pres.imgIntroSpongeInit.Visibility   = Visibility.Hidden;
                        pres.imgIntroSpongeAbsorb.Visibility = Visibility.Visible;
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelCurrentStep.Content   = Resources.PresSqueezingPhase;
                        pres.textBlockIntroduction.Text = Resources.PresSqueezingPhaseText;

                        pres.imgIntroSpongeAbsorb.Visibility  = Visibility.Hidden;
                        pres.imgIntroSpongeSqueeze.Visibility = Visibility.Visible;
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    /* calculate l parameter */
                    int l = (int)Math.Log((double)((rate + capacity) / 25), 2);

                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelCurrentStep.Content          = Resources.PresKeccakFPhase;
                        pres.textBlockIntroduction.Text        = string.Format(Resources.PresKeccakFPhaseText, l, (12 + 2 * l));
                        pres.labelIntroIterationAmount.Content = string.Format(Resources.PresKeccakFIterations, (12 + 2 * l));

                        pres.imgIntroSpongeSqueeze.Visibility  = Visibility.Hidden;
                        pres.imgIntroSpongeKeccakf2.Visibility = Visibility.Visible;
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelIntroIterationAmount.Content = "";
                        pres.imgIntroSpongeKeccakf2.Visibility = Visibility.Hidden;
                        pres.imgIntroStateMapping.Visibility   = Visibility.Visible;
                        pres.textBlockIntroduction.Text        = string.Format(Resources.PresKeccakFStateMapping, (capacity + rate), (capacity + rate) / 25);
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.buttonSkipIntro.Visibility      = Visibility.Hidden;
                        pres.imgIntroStateMapping.Visibility = Visibility.Hidden;
                        pres.labelIntroExecution.Visibility  = Visibility.Visible;
                        pres.textBlockIntroduction.Text      = "";
                        pres.labelCurrentPhase.Content       = "";
                        pres.labelCurrentStep.Content        = "";
                    }, null);

                    buttonNextClickedEvent = pres.buttonNextClickedEvent;
                    buttonNextClickedEvent.WaitOne();
                }

                if (!pres.skipPresentation && !pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelIntroExecution.Visibility = Visibility.Hidden;
                    }, null);
                }

                if (pres.skipPresentation || pres.skipIntro)
                {
                    pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        pres.labelIntroIterationAmount.Content = "";
                        pres.imgIntroFirstPage.Visibility      = Visibility.Hidden;
                        pres.imgIntroIntroduction.Visibility   = Visibility.Hidden;
                        pres.imgIntroSpongeInit.Visibility     = Visibility.Hidden;
                        pres.imgIntroSpongeAbsorb.Visibility   = Visibility.Hidden;
                        pres.imgIntroSpongeSqueeze.Visibility  = Visibility.Hidden;
                        pres.imgIntroSpongeKeccakf2.Visibility = Visibility.Hidden;
                        pres.imgIntroStateMapping.Visibility   = Visibility.Hidden;
                        pres.imgIntroExecution.Visibility      = Visibility.Hidden;
                        pres.buttonSkipIntro.Visibility        = Visibility.Hidden;
                        pres.labelIntroIntroduction.Visibility = Visibility.Hidden;
                        pres.labelIntroExecution.Visibility    = Visibility.Hidden;
                        pres.textBlockIntroduction.Text        = "";
                    }, null);
                }
            }

            #endregion

            /* hash input */
            output = KeccakHashFunction.Hash(input, outputLength, rate, capacity, ref pres, this);

            /* write output */
            OutputStreamwriter.Write(output);
            OutputStreamwriter.Close();

            #if _DEBUG_
            /* close debug stream and reset standard output */
            debugStreamWriter.Close();
            Console.SetOut(consoleOut);
            #endif

            /* hide button panel */
            if (pres.IsVisible)
            {
                pres.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                {
                    pres.spButtons.Visibility = Visibility.Hidden;
                }, null);
            }

            ProgressChanged(1, 1);
        }
Example #19
0
        private void process(int action, int padding)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (InputStream == null || InputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                byte[] inputbuffer  = new byte[8];
                byte[] outputbuffer = new byte[8];

                uint[] key      = new uint[4];
                long[] longKey  = new long[4];
                long   keybytes = inputKey.Length;
                GuiLogMessage("inputKey length [byte]: " + keybytes.ToString(), NotificationLevel.Debug);

                if (keybytes != 16)
                {
                    GuiLogMessage("Given key has false length. Please provide a key with 128 Bits length. Aborting now.", NotificationLevel.Error);
                    return;
                }

                if (settings.Version != 2)
                {
                    key[0] = BitConverter.ToUInt32(inputKey, 0);
                    key[1] = BitConverter.ToUInt32(inputKey, 4);
                    key[2] = BitConverter.ToUInt32(inputKey, 8);
                    key[3] = BitConverter.ToUInt32(inputKey, 12);
                }
                else
                {
                    longKey[0] = (long)BitConverter.ToUInt32(inputKey, 0);
                    longKey[1] = (long)BitConverter.ToUInt32(inputKey, 4);
                    longKey[2] = (long)BitConverter.ToUInt32(inputKey, 8);
                    longKey[3] = (long)BitConverter.ToUInt32(inputKey, 12);
                }

                //check for a valid IV
                if (this.inputIV == null)
                {
                    //create a trivial IV
                    inputIV = new byte[8];
                    if (settings.Mode != 0)
                    {
                        GuiLogMessage("WARNING - No IV provided. Using 0x000..00!", NotificationLevel.Warning);
                    }
                }
                byte[] IV = new byte[8];
                Array.Copy(inputIV, IV, Math.Min(inputIV.Length, IV.Length));

                DateTime startTime = DateTime.Now;

                uint[] vector     = new uint[2];
                long[] longVector = new long[2];

                CryptDelegate crypfunc = delegates[settings.Action * 3 + settings.Version];
                StatusChanged((int)teaimages[settings.Action * 3 + settings.Version]);

                outputStream = new CStreamWriter();
                ICryptoolStream inputdata = InputStream;

                if (action == 0)
                {
                    inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], 8);
                }

                CStreamReader reader = inputdata.CreateReader();

                GuiLogMessage("Starting " + ((action == 0)?"encryption":"decryption") + " [Keysize=128 Bits, Blocksize=64 Bits]", NotificationLevel.Info);

                if (settings.Mode == 0)    // ECB
                {
                    while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                    {
                        Bytes2Vector(vector, inputbuffer);
                        crypfunc(settings.Rounds, vector, key);
                        Vector2Bytes(vector, outputbuffer);
                        outputStream.Write(outputbuffer);
                    }
                }
                else if (settings.Mode == 1)    // CBC
                {
                    if (settings.Action == 0)
                    {
                        while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                        {
                            for (int i = 0; i < 8; i++)
                            {
                                inputbuffer[i] ^= IV[i];
                            }
                            Bytes2Vector(vector, inputbuffer);
                            crypfunc(settings.Rounds, vector, key);
                            Vector2Bytes(vector, outputbuffer);
                            for (int i = 0; i < 8; i++)
                            {
                                IV[i] = outputbuffer[i];
                            }
                            outputStream.Write(outputbuffer);
                        }
                    }
                    else
                    {
                        while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                        {
                            Bytes2Vector(vector, inputbuffer);
                            crypfunc(settings.Rounds, vector, key);
                            Vector2Bytes(vector, outputbuffer);
                            for (int i = 0; i < 8; i++)
                            {
                                outputbuffer[i] ^= IV[i];
                            }
                            for (int i = 0; i < 8; i++)
                            {
                                IV[i] = inputbuffer[i];
                            }
                            outputStream.Write(outputbuffer);
                        }
                    }
                }
                else if (settings.Mode == 2)    // CFB
                {
                    if (settings.Action == 0)
                    {
                        while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                        {
                            Bytes2Vector(vector, IV);
                            crypfunc(settings.Rounds, vector, key);
                            Vector2Bytes(vector, outputbuffer);
                            for (int i = 0; i < 8; i++)
                            {
                                outputbuffer[i] ^= inputbuffer[i];
                            }
                            for (int i = 0; i < 8; i++)
                            {
                                IV[i] = outputbuffer[i];
                            }
                            outputStream.Write(outputbuffer);
                        }
                    }
                    else
                    {
                        crypfunc = delegates[settings.Version]; // choose encrypt function
                        while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                        {
                            Bytes2Vector(vector, IV);
                            crypfunc(settings.Rounds, vector, key);
                            Vector2Bytes(vector, outputbuffer);
                            for (int i = 0; i < 8; i++)
                            {
                                outputbuffer[i] ^= inputbuffer[i];
                            }
                            for (int i = 0; i < 8; i++)
                            {
                                IV[i] = inputbuffer[i];
                            }
                            outputStream.Write(outputbuffer);
                        }
                    }
                }
                else if (settings.Mode == 3)                // OFB - encrypt = decrypt
                {
                    crypfunc = delegates[settings.Version]; // choose encrypt function
                    while (reader.Read(inputbuffer, 0, inputbuffer.Length) > 0 && !stop)
                    {
                        Bytes2Vector(vector, IV);
                        crypfunc(settings.Rounds, vector, key);
                        Vector2Bytes(vector, outputbuffer);
                        for (int i = 0; i < 8; i++)
                        {
                            IV[i] = outputbuffer[i];
                        }
                        for (int i = 0; i < 8; i++)
                        {
                            outputbuffer[i] ^= inputbuffer[i];
                        }
                        outputStream.Write(outputbuffer);
                    }
                }

                long     outbytes = outputStream.Length;
                DateTime stopTime = DateTime.Now;
                TimeSpan duration = stopTime - startTime;

                outputStream.Close();

                if (action == 1)
                {
                    outputStream = BlockCipherHelper.StripPadding(outputStream, settings.padmap[settings.Padding], 8) as CStreamWriter;
                }

                if (!stop)
                {
                    GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                    OnPropertyChanged("OutputStream");
                }
                else
                {
                    GuiLogMessage("Aborted!", NotificationLevel.Info);
                }
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Example #20
0
        /// <summary>
        /// Encrypts/Decrypts using OFB
        /// </summary>
        /// <param name="blockCipher"></param>
        /// <param name="cipherAction"></param>
        /// <param name="inputStream"></param>
        /// <param name="outputStream"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <param name="padding"></param>
        /// <param name="stop"></param>
        /// <param name="progressChanged"></param>
        /// <param name="lastInputBlock"></param>
        /// <param name="blocksize"></param>
        public static void ExecuteOFB(BlockCipher blockCipher,
                                      CipherAction cipherAction,
                                      ref ICrypToolStream inputStream,
                                      ref ICrypToolStream outputStream,
                                      byte[] key,
                                      byte[] iv,
                                      PaddingType padding,
                                      ref bool stop,
                                      ProgressChanged progressChanged,
                                      ref byte[] lastInputBlock,
                                      int blocksize = 8)
        {
            using (CStreamReader reader = inputStream.CreateReader())
            {
                using (CStreamWriter writer = new CStreamWriter())
                {
                    byte[] lastBlock = iv;
                    int    readcount = 0;

                    while (reader.Position < reader.Length && !stop)
                    {
                        //we always try to read a complete block
                        byte[] inputBlock = new byte[blocksize];
                        readcount = 0;
                        while ((readcount += reader.Read(inputBlock, readcount, blocksize - readcount)) < blocksize &&
                               reader.Position < reader.Length && !stop)
                        {
                            ;
                        }
                        if (stop)
                        {
                            return;
                        }

                        //Show progress in UI
                        progressChanged(reader.Position, reader.Length);

                        byte[] outputblock = null;
                        //we read a complete block
                        if (readcount == blocksize)
                        {
                            //Compute XOR with lastblock for OFB mode
                            if (cipherAction == CipherAction.Encrypt)
                            {
                                outputblock = blockCipher(lastBlock, key);
                                lastBlock   = outputblock;
                                outputblock = XOR(outputblock, inputBlock);
                            }
                            else
                            {
                                outputblock = blockCipher(lastBlock, key);
                                lastBlock   = outputblock;
                                outputblock = XOR(outputblock, inputBlock);
                            }
                        }
                        //we read an incomplete block, thus, we are at the end of the stream
                        else if (readcount > 0)
                        {
                            //Compute XOR with lastblock for CFB mode
                            if (cipherAction == CipherAction.Encrypt)
                            {
                                byte[] block = new byte[blocksize];
                                Array.Copy(inputBlock, 0, block, 0, readcount);
                                outputblock = blockCipher(lastBlock, key);
                                outputblock = XOR(outputblock, block);
                            }
                            else
                            {
                                byte[] block = new byte[blocksize];
                                Array.Copy(inputBlock, 0, block, 0, readcount);
                                outputblock = blockCipher(inputBlock, key);
                                outputblock = XOR(outputblock, lastBlock);
                            }
                        }

                        //check if it is the last block and we decrypt, thus, we have to remove the padding
                        if (reader.Position == reader.Length && cipherAction == CipherAction.Decrypt && padding != PaddingType.None)
                        {
                            int valid = StripPadding(outputblock, blocksize, padding, blocksize);
                            if (valid != blocksize)
                            {
                                byte[] newoutputblock = new byte[valid];
                                Array.Copy(outputblock, 0, newoutputblock, 0, valid);
                                outputblock = newoutputblock;
                            }
                            else if (valid == 0)
                            {
                                outputblock = null;
                            }
                        }

                        //if we crypted something, we output it
                        if (outputblock != null)
                        {
                            writer.Write(outputblock, 0, outputblock.Length);
                            //if we wrote to the stream, we memorize the last input block for the visualization
                            lastInputBlock = inputBlock;
                        }
                    }

                    writer.Flush();
                    outputStream = writer;
                }
            }
        }
Example #21
0
        public void Encrypt()
        {
            if (this.inputStream != null)
            {
                // Encrypt Stream
                try
                {
                    SymmetricAlgorithm p_alg = new PresentManaged();
                    ConfigureAlg(p_alg, true);

                    ICryptoolStream inputdata = InputStream;

                    inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);

                    CStreamReader reader = inputdata.CreateReader();

                    if ((this.presentation != null) & (p_alg.KeySize == 80))
                    {
                        byte[] block = new byte[8];
                        byte[] key   = (byte[])p_alg.Key.Clone();
                        int    r     = reader.Read(block, 0, 8);
                        if (reader.CanSeek)
                        {
                            reader.Position = 0;
                        }
                        if (r < 8)
                        {
                            for (int i = 0; i < r; i++)
                            {
                                block[7 - i] = block[r - i - 1];
                            }
                            byte p;
                            if (p_alg.Padding == PaddingMode.PKCS7)
                            {
                                p = (byte)(8 - r);
                            }
                            else
                            {
                                p = (byte)0;
                            }
                            for (int i = 0; i < 8 - r; i++)
                            {
                                block[i] = p;
                            }
                        }
                        this.presentation.Assign_Values(key, block);
                    }

                    ICryptoTransform p_encryptor = p_alg.CreateEncryptor();

                    outputStream        = new CStreamWriter();
                    p_crypto_stream_enc = new CryptoStream((Stream)reader, p_encryptor, CryptoStreamMode.Read);
                    byte[]   buffer = new byte[p_alg.BlockSize / 8];
                    int      bytesRead;
                    int      position  = 0;
                    DateTime startTime = DateTime.Now;
                    while ((bytesRead = p_crypto_stream_enc.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                    {
                        outputStream.Write(buffer, 0, bytesRead);
                        if ((int)(reader.Position * 100 / inputStream.Length) > position)
                        {
                            position = (int)(reader.Position * 100 / inputStream.Length);
                            Progress(reader.Position, inputStream.Length);
                        }
                    }
                    p_crypto_stream_enc.Flush();
                    // p_crypto_stream_enc.Close();

                    DateTime stopTime = DateTime.Now;
                    TimeSpan duration = stopTime - startTime;

                    outputStream.Close();

                    if (!stop)
                    {
                        GuiLogMessage("Encryption complete! (in: " + inputStream.Length.ToString() + " bytes, out: " + outputStream.Length.ToString() + " bytes)", NotificationLevel.Info);
                        GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                        OnPropertyChanged("OutputStream");
                    }
                    else
                    {
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                }
                catch (CryptographicException cryptographicException)
                {
                    // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
                    // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                    // the error messages will be doubled.
                    // As a workaround we set p_crypto_stream to null here.
                    p_crypto_stream_enc = null;
                    GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
                }
                catch (Exception exception)
                {
                    GuiLogMessage(exception.Message, NotificationLevel.Error);
                }
                finally
                {
                    Progress(1, 1);
                }
            }
        }
Example #22
0
        public void Decrypt()
        {
            if (this.inputStream != null)
            {
                // Decrypt Stream
                try
                {
                    SymmetricAlgorithm p_alg = new PresentManaged();
                    ConfigureAlg(p_alg, true);

                    ICryptoolStream inputdata = InputStream;

                    CStreamReader reader = inputdata.CreateReader();

                    ICryptoTransform p_decryptor = p_alg.CreateDecryptor();
                    outputStream        = new CStreamWriter();
                    p_crypto_stream_dec = new CryptoStream((Stream)reader, p_decryptor, CryptoStreamMode.Read);
                    byte[]   buffer = new byte[p_alg.BlockSize / 8];
                    int      bytesRead;
                    int      position  = 0;
                    DateTime startTime = DateTime.Now;

                    while ((bytesRead = p_crypto_stream_dec.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                    {
                        outputStream.Write(buffer, 0, bytesRead);
                        if ((int)(reader.Position * 100 / inputStream.Length) > position)
                        {
                            position = (int)(reader.Position * 100 / inputStream.Length);
                            Progress(reader.Position, inputStream.Length);
                        }
                    }

                    p_crypto_stream_dec.Flush();
                    p_crypto_stream_dec.Close();

                    DateTime stopTime = DateTime.Now;
                    TimeSpan duration = stopTime - startTime;

                    outputStream.Close();

                    if (settings.Action == 1)
                    {
                        outputStream = BlockCipherHelper.StripPadding(outputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8) as CStreamWriter;
                    }

                    if (!stop)
                    {
                        GuiLogMessage("Decryption complete! (in: " + inputStream.Length.ToString() + " bytes, out: " + outputStream.Length.ToString() + " bytes)", NotificationLevel.Info);
                        GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                        OnPropertyChanged("OutputStream");
                    }
                    else
                    {
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                }
                catch (CryptographicException cryptographicException)
                {
                    // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
                    // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                    // the error messages will be doubled.
                    // As a workaround we set p_crypto_stream to null here.
                    p_crypto_stream_dec = null;
                    GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
                }
                catch (Exception exception)
                {
                    GuiLogMessage(exception.Message, NotificationLevel.Error);
                }
                finally
                {
                    Progress(1, 1);
                }
            }
        }
Example #23
0
        private void process(int action)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (inputStream == null || inputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                ICryptoTransform   p_encryptor;
                SymmetricAlgorithm p_alg = new RC2CryptoServiceProvider();

                ConfigureAlg(p_alg);

                outputStreamWriter = new CStreamWriter();
                ICryptoolStream inputdata = InputStream;

                if (action == 0)
                {
                    inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                }

                CStreamReader reader = inputdata.CreateReader();

                GuiLogMessage("Starting " + ((settings.Action == 0)?"encryption":"decryption") + " [Keysize=" + p_alg.KeySize.ToString() + " Bits, Blocksize=" + p_alg.BlockSize.ToString() + " Bits]", NotificationLevel.Info);
                DateTime startTime = DateTime.Now;

                // special handling of OFB mode, as it's not available for RC2 in .Net
                if (settings.Mode == 3)    // OFB - bei OFB ist encrypt = decrypt, daher keine Fallunterscheidung
                {
                    p_encryptor = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);

                    byte[] IV = new byte[p_alg.IV.Length];
                    Array.Copy(p_alg.IV, IV, p_alg.IV.Length);
                    byte[] tmpInput   = BlockCipherHelper.StreamToByteArray(inputdata);
                    byte[] outputData = new byte[tmpInput.Length];

                    for (int pos = 0; pos <= tmpInput.Length - p_encryptor.InputBlockSize;)
                    {
                        int l = p_encryptor.TransformBlock(IV, 0, p_encryptor.InputBlockSize, outputData, pos);
                        for (int i = 0; i < l; i++)
                        {
                            IV[i] = outputData[pos + i];
                            outputData[pos + i] ^= tmpInput[pos + i];
                        }
                        pos += l;
                    }

                    outputStreamWriter.Write(outputData);
                }
                else
                {
                    p_encryptor     = (action == 0) ? p_alg.CreateEncryptor() : p_alg.CreateDecryptor();
                    p_crypto_stream = new CryptoStream((Stream)reader, p_encryptor, CryptoStreamMode.Read);

                    byte[] buffer = new byte[p_alg.BlockSize / 8];
                    int    bytesRead;

                    while ((bytesRead = p_crypto_stream.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                    {
                        outputStreamWriter.Write(buffer, 0, bytesRead);
                    }

                    p_crypto_stream.Flush();
                }

                outputStreamWriter.Close();

                DateTime stopTime = DateTime.Now;
                TimeSpan duration = stopTime - startTime;

                if (action == 1)
                {
                    outputStreamWriter = BlockCipherHelper.StripPadding(outputStreamWriter, settings.padmap[settings.Padding], p_alg.BlockSize / 8) as CStreamWriter;
                }

                if (!stop)
                {
                    GuiLogMessage(((settings.Action == 0) ? "Encryption" : "Decryption") + " complete! (in: " + InputStream.Length + " bytes, out: " + outputStreamWriter.Length + " bytes)", NotificationLevel.Info);
                    GuiLogMessage("Time used: " + duration, NotificationLevel.Debug);
                    OnPropertyChanged("OutputStream");
                }
                else
                {
                    GuiLogMessage("Aborted!", NotificationLevel.Info);
                }
            }
            catch (CryptographicException cryptographicException)
            {
                // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
                // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                // the error messages will be doubled.
                // As a workaround we set p_crypto_stream to null here.
                p_crypto_stream = null;
                GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Example #24
0
        /// <summary>
        /// Called by the execution engine threads to execute the internal plugin
        /// </summary>
        /// <param name="o"></param>
        internal void Execute(Object o)
        {
            var executionEngine = (ExecutionEngine)o;

            try
            {
                Stop = false;

                plugin.PreExecution();
                bool firstrun = true;

                while (true)
                {
                    resetEvent.WaitOne(10);
                    resetEvent.Reset();

                    //Check if we want to stop
                    if (Stop)
                    {
                        break;
                    }

                    // ################
                    // 0. If this is our first run and we are startable we start
                    // ################

                    //we are startable if we have NO input connectors
                    //Startable flag is deprecated now
                    if (firstrun && (InputConnectors.Count == 0 || HasOnlyOptionalUnconnectedInputs()))
                    {
                        firstrun = false;
                        try
                        {
                            PercentageFinished = 0;
                            GuiNeedsUpdate     = true;

                            Plugin.Execute();
                            executionEngine.ExecutionCounter++;

                            PercentageFinished = 1;
                            GuiNeedsUpdate     = true;
                        }
                        catch (Exception ex)
                        {
                            executionEngine.GuiLogMessage(
                                String.Format(Resources.PluginModel_Execute_An_error_occured_while_executing___0______1_, Name, ex.Message),
                                NotificationLevel.Error);
                            State          = PluginModelState.Error;
                            GuiNeedsUpdate = true;
                        }
                        continue;
                    }

                    var breakit       = false;
                    var atLeastOneNew = false;

                    // ################
                    // 1. Check if we may execute
                    // ################

                    //Check if all necessary inputs are set
                    foreach (ConnectorModel connectorModel in InputConnectors)
                    {
                        if (!connectorModel.IControl &&
                            (connectorModel.IsMandatory || connectorModel.InputConnections.Count > 0))
                        {
                            if (connectorModel.DataQueue.Count == 0 && connectorModel.LastData == null)
                            {
                                breakit = true;
                                continue;
                            }
                            if (connectorModel.DataQueue.Count > 0)
                            {
                                atLeastOneNew = true;
                            }
                        }
                    }

                    //Check if all outputs are free
                    foreach (ConnectorModel connectorModel in OutputConnectors)
                    {
                        if (!connectorModel.IControl)
                        {
                            foreach (ConnectionModel connectionModel in connectorModel.OutputConnections)
                            {
                                if (connectionModel.To.DataQueue.Count > 0)
                                {
                                    breakit = true;
                                }
                            }
                        }
                    }

                    //Gate is a special case: here we need all new data
                    if (PluginType.FullName.Equals("Gate.Gate"))
                    {
                        foreach (ConnectorModel connectorModel in InputConnectors)
                        {
                            if (connectorModel.InputConnections.Count > 0 && connectorModel.DataQueue.Count == 0)
                            {
                                breakit = true;
                            }
                        }
                    }

                    if (breakit || !atLeastOneNew)
                    {
                        continue;
                    }

                    // ################
                    //2. Fill all Inputs of the plugin, if this fails break the loop run
                    // ################
                    foreach (ConnectorModel connectorModel in InputConnectors)
                    {
                        try
                        {
                            if ((connectorModel.DataQueue.Count == 0 && connectorModel.LastData == null) || connectorModel.InputConnections.Count == 0)
                            {
                                continue;
                            }

                            object data;

                            if (connectorModel.DataQueue.Count > 0)
                            {
                                data = connectorModel.DataQueue.Dequeue();
                            }
                            else
                            {
                                continue;
                            }

                            if (data == null)
                            {
                                continue;
                            }

                            //Implicit conversions:

                            //Cast from BigInteger -> Integer
                            if ((connectorModel.ConnectorType.FullName == "System.Int32" ||
                                 connectorModel.ConnectorType.FullName == "System.Int64") &&
                                data.GetType().FullName == "System.Numerics.BigInteger")
                            {
                                try
                                {
                                    data = (int)((BigInteger)data);
                                }
                                catch (OverflowException)
                                {
                                    State = PluginModelState.Error;
                                    WorkspaceModel.ExecutionEngine.GuiLogMessage(String.Format(Resources.PluginModel_Execute_Number_of__0__too_big_for__1____2_, connectorModel.Name, Name, data), NotificationLevel.Error);
                                }
                            }
                            //Cast from Integer -> BigInteger
                            else if (connectorModel.ConnectorType.FullName == "System.Numerics.BigInteger" &&
                                     (data.GetType().FullName == "System.Int32" || data.GetType().FullName == "System.Int64"))
                            {
                                data = new BigInteger((int)data);
                            }
                            //Cast from System.Byte[] -> System.String (UTF8)
                            else if (connectorModel.ConnectorType.FullName == "System.String" && data.GetType().FullName == "System.Byte[]")
                            {
                                var encoding = new UTF8Encoding();
                                data = encoding.GetString((byte[])data);
                            }
                            //Cast from System.String (UTF8) -> System.Byte[]
                            else if (connectorModel.ConnectorType.FullName == "System.Byte[]" && data.GetType().FullName == "System.String")
                            {
                                var encoding = new UTF8Encoding();
                                data = encoding.GetBytes((string)data);
                            }
                            //Cast from System.String (UTF8) -> ICryptoolStream
                            else if (connectorModel.ConnectorType.FullName == "Cryptool.PluginBase.IO.ICryptoolStream" && data.GetType().FullName == "System.String")
                            {
                                var writer = new CStreamWriter();
                                var str    = (string)data;
                                if (str.Length > MaxStrStreamConversionLength)
                                {
                                    str = str.Substring(0, MaxStrStreamConversionLength);
                                }
                                var encoding = new UTF8Encoding();
                                writer.Write(encoding.GetBytes(str));
                                writer.Close();
                                data = writer;
                            }
                            //Cast from ICryptoolStream -> System.String (UTF8)
                            else if (connectorModel.ConnectorType.FullName == "System.String" && data.GetType().FullName == "Cryptool.PluginBase.IO.CStreamWriter")
                            {
                                var writer = (CStreamWriter)data;
                                using (var reader = writer.CreateReader())
                                {
                                    var buffer     = new byte[MaxStrStreamConversionLength];
                                    var readamount = reader.Read(buffer, 0, MaxStrStreamConversionLength);
                                    if (readamount > 0)
                                    {
                                        var encoding = new UTF8Encoding();
                                        var str      = encoding.GetString(buffer, 0, readamount);
                                        data = str;
                                    }
                                    else
                                    {
                                        data = String.Empty;
                                    }
                                }
                            }
                            //Cast to System.String
                            else if (connectorModel.ConnectorType.FullName == "System.String")
                            {
                                //Cast from System.Boolean -> System.String
                                if (data.GetType().FullName == "System.Boolean")
                                {
                                    data = ((Boolean)data).ToString();
                                }
                                //Cast from System.Int32 -> System.String
                                else if (data.GetType().FullName == "System.Int32")
                                {
                                    data = ((Int32)data).ToString();
                                }
                                //Cast from System.Int64 -> System.String
                                else if (data.GetType().FullName == "System.Int64")
                                {
                                    data = ((Int64)data).ToString();
                                }
                                //Cast from System.Numerics.BigInteger -> System.String
                                else if (data.GetType().FullName == "System.Numerics.BigInteger")
                                {
                                    data = ((BigInteger)data).ToString();
                                }
                            }

                            //now set the data
                            if (connectorModel.property == null)
                            {
                                connectorModel.property =
                                    Plugin.GetType().GetProperty(connectorModel.PropertyName);
                            }
                            connectorModel.property.SetValue(Plugin, data, null);
                        }
                        catch (Exception ex)
                        {
                            executionEngine.GuiLogMessage(
                                String.Format(Resources.PluginModel_Execute_An_error_occured_while_setting_value_of_connector___0___of___1_____2_, connectorModel.Name, Name, ex.Message), NotificationLevel.Error);
                            State          = PluginModelState.Error;
                            GuiNeedsUpdate = true;
                        }
                    }

                    // ################
                    //3. Execute
                    // ################
                    try
                    {
                        if (executionEngine.SleepTime > 0)
                        {
                            Thread.Sleep(executionEngine.SleepTime);
                        }

                        PercentageFinished = 0;
                        GuiNeedsUpdate     = true;

                        Plugin.Execute();
                        executionEngine.ExecutionCounter++;

                        if (plugin.GetAutoAssumeFullEndProgressAttribute())
                        {
                            PercentageFinished = 1;
                            GuiNeedsUpdate     = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        executionEngine.GuiLogMessage(
                            String.Format(Resources.PluginModel_Execute_An_error_occured_while_executing____0______1__, Name, ex.Message), NotificationLevel.Error);
                        State          = PluginModelState.Error;
                        GuiNeedsUpdate = true;
                    }

                    // ################
                    // 4. Set all connectorModels belonging to this pluginModel to inactive
                    // ################
                    foreach (ConnectorModel connectorModel in InputConnectors)
                    {
                        foreach (var connectionModel in connectorModel.InputConnections)
                        {
                            connectionModel.Active         = false;
                            connectionModel.GuiNeedsUpdate = true;
                        }
                    }

                    // ################
                    // 5. let all plugins before this check if it may execute
                    // ################
                    foreach (ConnectorModel connectorModel in InputConnectors)
                    {
                        foreach (ConnectionModel connectionModel in connectorModel.InputConnections)
                        {
                            connectionModel.From.PluginModel.resetEvent.Set();
                        }
                    }
                }
                plugin.PostExecution();
            }
            catch (Exception ex)
            {
                executionEngine.GuiLogMessage(
                    String.Format(Resources.PluginModel_Execute_An_error_occured_while_executing___0______1_, Name, ex.Message),
                    NotificationLevel.Error);
                State = PluginModelState.Error;
            }
        }
 public void Execute()
 {
     try
     {
         if (settings.NumberOfPacketsToBeCreated == 0)
         {
             GuiLogMessage("ERROR. No number of packets to be created given. Aborting now.", NotificationLevel.Error);
             return;
         }
         rnd = new Random();
         string successMessage = string.Empty;
         packetCounter = 0;
         outputStream  = new CStreamWriter();
         outputStream.Write(header, 0, header.Length);
         // IPv4 packets are requested
         if (settings.Action == 0)
         {
             DateTime startTime = DateTime.Now;
             for (int i = 0; i < settings.NumberOfPacketsToBeCreated; i++)
             {
                 if (stop)
                 {
                     break;
                 }
                 Progress(i, settings.NumberOfPacketsToBeCreated);
                 byte[] tmp = generateIPPackets();
                 outputStream.Write(tmp, 0, tmp.Length);
                 packetCounter++;
             }
             DateTime stopTime = DateTime.Now;
             TimeSpan duration = stopTime - startTime;
             if (packetCounter == 1)
             {
                 successMessage = "Successfully created " + packetCounter + " IPv4 packet.";
             }
             else
             {
                 successMessage = "Successfully created " + packetCounter.ToString("#,#", CultureInfo.InstalledUICulture) + " IPv4 packets.";
             }
             if (!stop)
             {
                 GuiLogMessage(successMessage, NotificationLevel.Info);
                 GuiLogMessage("Time used [h:min:sec]: " + duration, NotificationLevel.Info);
                 outputStream.Close();
                 OnPropertyChanged("OutputStream");
             }
         }
         // ARP packets are requested
         if (settings.Action == 1)
         {
             DateTime startTime = DateTime.Now;
             for (int i = 0; i < settings.NumberOfPacketsToBeCreated; i++)
             {
                 if (stop)
                 {
                     break;
                 }
                 Progress(i, settings.NumberOfPacketsToBeCreated);
                 byte[] tmp = generateARPRequestPackets();
                 //outputList.Add(tmp);
                 outputStream.Write(tmp, 0, tmp.Length);
                 packetCounter++;
             }
             DateTime stopTime = DateTime.Now;
             TimeSpan duration = stopTime - startTime;
             if (packetCounter == 1)
             {
                 successMessage = "Successfully created " + packetCounter + " ARP request packet.";
             }
             else
             {
                 successMessage = "Successfully created " + packetCounter.ToString("#,#", CultureInfo.InstalledUICulture) + " ARP request packets.";
             }
             if (!stop)
             {
                 GuiLogMessage(successMessage, NotificationLevel.Info);
                 GuiLogMessage("Time used [h:min:sec]: " + duration, NotificationLevel.Info);
                 outputStream.Close();
                 OnPropertyChanged("OutputStream");
             }
         }
         if (stop)
         {
             outputStream.Close();
             GuiLogMessage("Aborted!", NotificationLevel.Info);
         }
     }
     catch (Exception exc)
     {
         GuiLogMessage(exc.Message, NotificationLevel.Error);
     }
     finally
     {
         Progress(1, 1);
     }
 }
Example #26
0
        private void process(int action)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (InputStream == null || InputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                ICryptoTransform   p_encryptor;
                SymmetricAlgorithm p_alg = null;

                if (settings.TripleDES)
                {
                    p_alg = new TripleDESCryptoServiceProvider();
                }
                else
                {
                    p_alg = new DESCryptoServiceProvider();
                }

                ConfigureAlg(p_alg);

                outputStreamWriter = new CStreamWriter();
                ICryptoolStream inputdata = InputStream;

                // append 1-0 padding (special handling, as it's not present in System.Security.Cryptography.PaddingMode)
                if (action == 0)
                {
                    inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                }

                CStreamReader reader = inputdata.CreateReader();

                //GuiLogMessage("Starting encryption [Keysize=" + p_alg.KeySize.ToString() + " Bits, Blocksize=" + p_alg.BlockSize.ToString() + " Bits]", NotificationLevel.Info);
                DateTime startTime = DateTime.Now;

                // special handling of OFB mode, as it's not available for DES in .Net
                if (settings.Mode == 3)    // OFB - bei OFB ist encrypt = decrypt, daher keine Fallunterscheidung
                {
                    try
                    {
                        p_encryptor = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);
                    }
                    catch
                    {
                        //dirty hack to allow weak keys:
                        MethodInfo mi  = p_alg.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance);
                        object[]   Par = { p_alg.Key, p_alg.Mode, p_alg.IV, p_alg.FeedbackSize, 0 };
                        p_encryptor = mi.Invoke(p_alg, Par) as ICryptoTransform;
                    }

                    byte[] IV = new byte[p_alg.IV.Length];
                    Array.Copy(p_alg.IV, IV, p_alg.IV.Length);
                    byte[] tmpInput   = BlockCipherHelper.StreamToByteArray(inputdata);
                    byte[] outputData = new byte[tmpInput.Length];

                    for (int pos = 0; pos <= tmpInput.Length - p_encryptor.InputBlockSize;)
                    {
                        int l = p_encryptor.TransformBlock(IV, 0, p_encryptor.InputBlockSize, outputData, pos);
                        for (int i = 0; i < l; i++)
                        {
                            IV[i] = outputData[pos + i];
                            outputData[pos + i] ^= tmpInput[pos + i];
                        }
                        pos += l;
                    }

                    outputStreamWriter.Write(outputData);
                }
                else
                {
                    try
                    {
                        p_encryptor = (action == 0) ? p_alg.CreateEncryptor() : p_alg.CreateDecryptor();
                    }
                    catch
                    {
                        //dirty hack to allow weak keys:
                        MethodInfo mi = (action == 0) ?  p_alg.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance)
                            : p_alg.GetType().GetMethod("_NewDecryptor", BindingFlags.NonPublic | BindingFlags.Instance);;
                        object[] par = { p_alg.Key, p_alg.Mode, p_alg.IV, p_alg.FeedbackSize, 0 };
                        p_encryptor = mi.Invoke(p_alg, par) as ICryptoTransform;
                    }
                    p_crypto_stream = new CryptoStream((Stream)reader, p_encryptor, CryptoStreamMode.Read);

                    byte[] buffer = new byte[p_alg.BlockSize / 8];
                    int    bytesRead;

                    while ((bytesRead = p_crypto_stream.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                    {
                        //// remove 1-0 padding (special handling, as it's not present in System.Security.Cryptography.PaddingMode)
                        //if (action == 1 && settings.Padding == 5 && reader.Position == reader.Length)
                        //    bytesRead = BlockCipherHelper.StripPadding(buffer, bytesRead, BlockCipherHelper.PaddingType.OneZeros, buffer.Length);

                        outputStreamWriter.Write(buffer, 0, bytesRead);
                    }

                    p_crypto_stream.Flush();
                }

                outputStreamWriter.Close();

                //DateTime stopTime = DateTime.Now;
                //TimeSpan duration = stopTime - startTime;

                if (action == 1)
                {
                    outputStreamWriter = BlockCipherHelper.StripPadding(outputStreamWriter, settings.padmap[settings.Padding], p_alg.BlockSize / 8) as CStreamWriter;
                }

                if (!stop)
                {
                    //GuiLogMessage("Encryption complete! (in: " + reader.Length.ToString() + " bytes, out: " + outputStreamWriter.Length.ToString() + " bytes)", NotificationLevel.Info);
                    //GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                    OnPropertyChanged("OutputStream");
                }
                else
                {
                    GuiLogMessage("Aborted!", NotificationLevel.Info);
                }
            }
            catch (CryptographicException cryptographicException)
            {
                p_crypto_stream = null;
                string msg = cryptographicException.Message;

                // Workaround for misleading padding error message
                if (msg.StartsWith("Ungültige Daten"))
                {
                    msg = "Das Padding ist ungültig und kann nicht entfernt werden.";
                }

                GuiLogMessage(msg, NotificationLevel.Error);
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Example #27
0
        private void process(int action)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (InputStream == null || InputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                SymmetricAlgorithm p_alg = null;
                if (settings.CryptoAlgorithm == 1)
                {
                    p_alg = new RijndaelManaged();
                }
                else
                {
                    p_alg = new AesCryptoServiceProvider();
                }

                ConfigureAlg(p_alg);

                ICryptoTransform p_encryptor = null;
                switch (action)
                {
                case 0:
                    p_encryptor = p_alg.CreateEncryptor();
                    break;

                case 1:
                    p_encryptor = p_alg.CreateDecryptor();
                    break;
                }

                outputStreamWriter = new CStreamWriter();

                ICrypToolStream inputdata = InputStream;

                string mode = action == 0 ? "encryption" : "decryption";
                long   inbytes, outbytes;

                //GuiLogMessage("Starting " + mode + " [Keysize=" + p_alg.KeySize.ToString() + " Bits, Blocksize=" + p_alg.BlockSize.ToString() + " Bits]", NotificationLevel.Info);

                DateTime startTime = DateTime.Now;

                // special handling of OFB mode, as it's not available for AES in .Net
                if (settings.Mode == 3)    // OFB - bei OFB ist encrypt = decrypt, daher keine Fallunterscheidung
                {
                    if (action == 0)
                    {
                        inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                    }

                    ICryptoTransform encrypt = p_alg.CreateEncryptor(p_alg.Key, p_alg.IV);

                    byte[] IV = new byte[p_alg.IV.Length];
                    Array.Copy(p_alg.IV, IV, p_alg.IV.Length);
                    byte[] tmpInput   = BlockCipherHelper.StreamToByteArray(inputdata);
                    byte[] outputData = new byte[tmpInput.Length];

                    for (int pos = 0; pos <= tmpInput.Length - encrypt.InputBlockSize;)
                    {
                        int l = encrypt.TransformBlock(IV, 0, encrypt.InputBlockSize, outputData, pos);
                        for (int i = 0; i < l; i++)
                        {
                            IV[i] = outputData[pos + i];
                            outputData[pos + i] ^= tmpInput[pos + i];
                        }
                        pos += l;
                    }

                    int validBytes = (int)inputdata.Length;

                    if (action == 1)
                    {
                        validBytes = BlockCipherHelper.StripPadding(outputData, validBytes, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                    }

                    encrypt.Dispose();
                    outputStreamWriter.Write(outputData, 0, validBytes);
                    inbytes = inputdata.Length;
                }
                else if (settings.Mode == 4)
                {
                    if (action == 0)
                    {
                        inputdata = BlockCipherHelper.AppendPadding(InputStream, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                    }

                    byte[] tmpInput = BlockCipherHelper.StreamToByteArray(inputdata);

                    var cipher       = new AesEngine();
                    var eaxCipher    = new EaxBlockCipher(cipher);
                    var keyParameter = new KeyParameter(p_alg.Key);
                    var parameter    = new ParametersWithIV(keyParameter, p_alg.IV);
                    eaxCipher.Init((action == 0) ? true : false, parameter);

                    byte[] datOut = new byte[eaxCipher.GetOutputSize(tmpInput.Length)];
                    int    outOff = eaxCipher.ProcessBytes(tmpInput, 0, tmpInput.Length, datOut, 0);
                    outOff += eaxCipher.DoFinal(datOut, outOff);

                    int validBytes = (int)eaxCipher.GetOutputSize(tmpInput.Length);
                    if (action == 1)
                    {
                        validBytes = BlockCipherHelper.StripPadding(datOut, validBytes, settings.padmap[settings.Padding], p_alg.BlockSize / 8);
                    }
                    outputStreamWriter.Write(datOut, 0, validBytes);
                    inbytes = inputdata.Length;
                }
                else
                {
                    // append 1-0 padding (special handling, as it's not present in System.Security.Cryptography.PaddingMode)
                    if (action == 0 && settings.Padding == 5)
                    {
                        inputdata = BlockCipherHelper.AppendPadding(InputStream, BlockCipherHelper.PaddingType.OneZeros, p_alg.BlockSize / 8);
                    }

                    CStreamReader reader = inputdata.CreateReader();

                    p_crypto_stream = new CryptoStream(reader, p_encryptor, CryptoStreamMode.Read);
                    byte[] buffer = new byte[p_alg.BlockSize / 8];
                    int    bytesRead;
                    int    position = 0;

                    while ((bytesRead = p_crypto_stream.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                    {
                        // remove 1-0 padding (special handling, as it's not present in System.Security.Cryptography.PaddingMode)
                        if (action == 1 && settings.Padding == 5 && reader.Position == reader.Length)
                        {
                            bytesRead = BlockCipherHelper.StripPadding(buffer, bytesRead, BlockCipherHelper.PaddingType.OneZeros, buffer.Length);
                        }

                        outputStreamWriter.Write(buffer, 0, bytesRead);

                        if ((int)(reader.Position * 100 / reader.Length) > position)
                        {
                            position = (int)(reader.Position * 100 / reader.Length);
                            ProgressChanged(reader.Position, reader.Length);
                        }
                    }

                    p_crypto_stream.Flush();
                    inbytes = reader.Length;
                }

                outbytes = outputStreamWriter.Length;

                DateTime stopTime = DateTime.Now;
                TimeSpan duration = stopTime - startTime;
                // (outputStream as CrypToolStream).FinishWrite();

                if (!stop)
                {
                    mode = action == 0 ? "Encryption" : "Decryption";
                    //GuiLogMessage(mode + " complete! (in: " + inbytes + " bytes, out: " + outbytes + " bytes)", NotificationLevel.Info);
                    //GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                    outputStreamWriter.Close();
                    OnPropertyChanged("OutputStream");
                }

                if (stop)
                {
                    outputStreamWriter.Close();
                    GuiLogMessage("Aborted!", NotificationLevel.Info);
                }
            }
            catch (CryptographicException cryptographicException)
            {
                // TODO: For an unknown reason p_crypto_stream cannot be closed after exception.
                // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                // the error messages will be doubled.
                // As a workaround we set p_crypto_stream to null here.
                p_crypto_stream = null;

                string msg = cryptographicException.Message;

                // Workaround for misleading german error message
                if (msg == "Die Zeichenabstände sind ungültig und können nicht entfernt werden.")
                {
                    msg = "Das Padding ist ungültig und kann nicht entfernt werden.";
                }

                GuiLogMessage(msg, NotificationLevel.Error);
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Example #28
0
 /// <summary>
 /// Function to write data to the OutputStream.
 /// </summary>
 /// <param name="value">the value that should be written</param>
 private void WriteOutput(ulong value)
 {
     outputStreamWriter.Write(encoding.GetBytes(value.ToString()));
 }
Example #29
0
 /// <summary>
 /// Function to write data to the DebugStream.
 /// </summary>
 /// <param name="str">the string that should be written</param>
 private void WriteDebug(string str)
 {
     debugDataWriter.Write(encoding.GetBytes(str));
 }
Example #30
0
        private void process(int action, int padding)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (inputStream == null || inputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                outputStreamWriter = new CStreamWriter();

                long inputbytes = inputStream.Length;
                GuiLogMessage("inputStream length [bytes]: " + inputStream.Length.ToString(), NotificationLevel.Debug);

                int bytesRead  = 0;
                int blocksRead = 0;
                int position;
                int blocks;

                // get number of blocks
                if (((int)inputbytes % 8) == 0)
                {
                    blocks = (int)inputbytes / 8;
                }
                else
                {
                    blocks = (int)Math.Round(inputbytes / 8 + 0.4, 0) + 1;
                }

                byte[] inputbuffer  = new byte[8 * blocks];
                byte[] outputbuffer = new byte[4];
                GuiLogMessage("# of blocks: " + blocks.ToString(), NotificationLevel.Debug);

                using (CStreamReader reader = inputStream.CreateReader())
                {
                    //read input
                    //GuiLogMessage("Current position: " + inputStream.Position.ToString(), NotificationLevel.Debug);
                    for (blocksRead = 0; blocksRead <= blocks - 1; blocksRead++)
                    {
                        for (position = bytesRead; position <= (blocksRead * 8 + 7); position++)
                        {
                            // no padding to do
                            if (position < inputbytes)
                            {
                                inputbuffer[position] = (byte)reader.ReadByte();
                            }
                            else // padding to do!
                            {
                                if (padding == 0)
                                {
                                    // padding with zeros
                                    inputbuffer[position] = 48;
                                }
                                else if (padding == 2)
                                {
                                    // padding with PKCS7
                                    int temp = 8 - (int)inputbytes % 8 + 48;
                                    inputbuffer[position] = (byte)temp;
                                }
                                else
                                {
                                    // no padding
                                    inputbuffer[position] = (byte)reader.ReadByte();
                                    GuiLogMessage("Byte is: " + inputbuffer[position].ToString(), NotificationLevel.Info);
                                }
                            }
                            bytesRead++;
                            //GuiLogMessage("Current position: " + inputStream.Position.ToString(), NotificationLevel.Debug);
                            //GuiLogMessage("Content of buffer[" + position + "]: " + buffer[position].ToString(), NotificationLevel.Debug);
                        }
                    }

                    //GuiLogMessage("vector[0] before coding: " + vector[0].ToString(), NotificationLevel.Debug);
                    //GuiLogMessage("vector[1] before coding: " + vector[1].ToString(), NotificationLevel.Debug);

                    uint[] key      = new uint[4];
                    long   keybytes = inputKey.Length;
                    GuiLogMessage("inputKey length [byte]: " + keybytes.ToString(), NotificationLevel.Debug);

                    if (keybytes != 16)
                    {
                        GuiLogMessage("Given key has false length. Please provide a key with 128 Bits length. Aborting now.", NotificationLevel.Error);
                        return;
                    }
                    else
                    {
                        key[0] = BitConverter.ToUInt32(inputKey, 0);
                        key[1] = BitConverter.ToUInt32(inputKey, 4);
                        key[2] = BitConverter.ToUInt32(inputKey, 8);
                        key[3] = BitConverter.ToUInt32(inputKey, 12);
                    }

                    //encryption or decryption
                    GuiLogMessage("Action is: " + action, NotificationLevel.Debug);
                    DateTime startTime = DateTime.Now;

                    uint[] vector = new uint[2];

                    if (action == 0)
                    {
                        StatusChanged((int)HIGHTImage.Encode);
                        GuiLogMessage("Starting encryption [Keysize=128 Bits, Blocksize=64 Bits]", NotificationLevel.Info);
                        for (int i = 0; i <= blocks - 1; i++)
                        {
                            vector[0] = BitConverter.ToUInt32(inputbuffer, (i * 8));
                            vector[1] = BitConverter.ToUInt32(inputbuffer, (i * 8 + 4));

                            //GuiLogMessage("vector[0]: " + vector[0].ToString("X"), NotificationLevel.Info);
                            //GuiLogMessage("vector[1]: " + vector[1].ToString("X"), NotificationLevel.Info);

                            vector = general_test(vector, key, 0);

                            //write buffer to output stream
                            outputbuffer = BitConverter.GetBytes(vector[0]);
                            outputStreamWriter.Write(outputbuffer, 0, 4);
                            outputbuffer = BitConverter.GetBytes(vector[1]);
                            outputStreamWriter.Write(outputbuffer, 0, 4);
                        }
                    }
                    else if (action == 1)
                    {
                        StatusChanged((int)HIGHTImage.Decode);
                        GuiLogMessage("Starting decryption [Keysize=128 Bits, Blocksize=64 Bits]", NotificationLevel.Info);
                        for (int i = 0; i <= blocks - 1; i++)
                        {
                            vector[0] = BitConverter.ToUInt32(inputbuffer, i * 8);
                            vector[1] = BitConverter.ToUInt32(inputbuffer, i * 8 + 4);

                            vector = general_test(vector, key, 1);

                            //write buffer to output stream
                            outputbuffer = BitConverter.GetBytes(vector[0]);
                            outputStreamWriter.Write(outputbuffer, 0, 4);
                            outputbuffer = BitConverter.GetBytes(vector[1]);
                            outputStreamWriter.Write(outputbuffer, 0, 4);
                        }
                    }

                    /*while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0 && !stop)
                     * {
                     *  outputStream.Write(buffer, 0, bytesRead);
                     *  if ((int)(inputStream.Position * 100 / inputStream.Length) > position)
                     *  {
                     *      position = (int)(inputStream.Position * 100 / inputStream.Length);
                     *      //ProgressChanged(inputStream.Position, inputStream.Length);
                     *  }
                     * }*/

                    long     outbytes = outputStreamWriter.Length;
                    DateTime stopTime = DateTime.Now;
                    TimeSpan duration = stopTime - startTime;
                    //(outputStream as CryptoolStream).FinishWrite();

                    if (!stop)
                    {
                        if (action == 0)
                        {
                            GuiLogMessage("Encryption complete! (in: " + inputStream.Length.ToString() + " bytes, out: " + outbytes.ToString() + " bytes)", NotificationLevel.Info);
                        }
                        else
                        {
                            GuiLogMessage("Decryption complete! (in: " + inputStream.Length.ToString() + " bytes, out: " + outbytes.ToString() + " bytes)", NotificationLevel.Info);
                        }
                        GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                        outputStreamWriter.Close();
                        OnPropertyChanged("OutputStream");
                    }

                    if (stop)
                    {
                        outputStreamWriter.Close();
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                }
            }

            /*catch (CryptographicException cryptographicException)
             * {
             *  // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
             *  // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
             *  // the error messages will be doubled.
             *  // As a workaround we set p_crypto_stream to null here.
             *  p_crypto_stream = null;
             *  //GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
             * }*/
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }