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(); } }
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); }
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); } }
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)); }
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); }
public void Stop() { if (devices.Count > 0) { WinPcapDevice dev = devices[settings.Device]; dev.StopCapture(); dev.Close(); } if (writer != null && !writer.IsClosed) { writer.Close(); } ProgressChanged(1, 1); }
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); }
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"); }
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; } }
private void Reset() { try { stop = false; inputKey = null; outputStream = null; if (outputStream != null) { outputStream.Flush(); outputStream.Close(); outputStream.Dispose(); outputStream = null; } } catch (Exception ex) { GuiLogMessage(ex.Message, NotificationLevel.Error); } }
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); } } }
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); } }
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); } }
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); }
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); } }
/// <summary> /// En- or decrypt input stream with ChaCha. /// </summary> /// <param name="key">The secret 128-bit or 256-bit key. A 128-bit key will be expanded into a 256-bit key by concatenation with itself.</param> /// <param name="iv">Initialization vector (DJB version: 64-bit, IETF version: 96-bit)</param> /// <param name="initialCounter">Initial counter (DJB version: 64-bit, IETF version: 32-bit)</param> /// <param name="settings">Chosen Settings in the Plugin workspace. Includes Rounds and Version property.</param> /// <param name="input">Input stream</param> /// <param name="output">Output stream</param> /// <param name="keystreamWriter">Keystream Output stream</param> private void Xcrypt(byte[] key, byte[] iv, ulong initialCounter, ChaChaSettings settings, ICryptoolStream input, CStreamWriter output, CStreamWriter keystreamOutput) { if (!(key.Length == 32 || key.Length == 16)) { throw new ArgumentOutOfRangeException("key", key.Length, "Key must be exactly 128-bit or 256-bit."); } if (iv.Length != settings.Version.IVBits / 8) { throw new ArgumentOutOfRangeException("iv", iv.Length, $"IV must be exactly {settings.Version.IVBits}-bit."); } void AssertCounter(ulong counter, ulong max) { if (!(0 <= counter && counter <= max)) { throw new ArgumentOutOfRangeException("initialCounter", counter, $"Initial counter must be between 0 and {max}."); } } if (settings.Version == Version.DJB) { AssertCounter(initialCounter, ulong.MaxValue); } else if (settings.Version == Version.IETF) { AssertCounter(initialCounter, uint.MaxValue); } // The first 512-bit state. Reused for counter insertion. uint[] firstState = State(key, iv, initialCounter, settings.Version); // Buffer to read 512-bit input block byte[] inputBytes = new byte[64]; CStreamReader inputReader = input.CreateReader(); // byte size of input long inputSize = inputReader.Length; // one keystream block is 64 bytes (512 bit) TotalKeystreamBlocks = (int)Math.Ceiling((double)(inputSize) / 64); ulong blockCounter = initialCounter; int read = inputReader.Read(inputBytes); while (read != 0) { // Will hold the state during each keystream uint[] state = (uint[])firstState.Clone(); InsertCounter(ref state, blockCounter, settings.Version); ChaChaHash(ref state, settings.Rounds); byte[] keystream = ByteUtil.ToByteArray(state); keystreamOutput.Write(keystream); byte[] c = ByteUtil.XOR(keystream, inputBytes, read); output.Write(c); // Don't add to InputMessage during diffusion run because it won't // return a different list during the diffusion run. if (!DiffusionExecution) { InputMessage.AddRange(inputBytes.Take(read)); } Keystream.AddRange(keystream.Take(read)); Output.AddRange(c); blockCounter++; // Read next input block read = inputReader.Read(inputBytes); } inputReader.Dispose(); output.Flush(); output.Close(); output.Dispose(); keystreamOutput.Flush(); keystreamOutput.Close(); keystreamOutput.Dispose(); }
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); } }
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); } }
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); } } }
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); } }
/// <summary> /// Called every time this plugin is run in the workflow execution. /// </summary> public void Execute() { ProgressChanged(0, 100); #region lokale variablen const int BUFFERSIZE = 524288; int exitcode = -1; string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string solverExe = settings.solverExe[(int)settings.SatString]; //GuiLogMessage(path + "\\" + solverExe, NotificationLevel.Debug); outputResultStream = new CStreamWriter(); inputStream = InputStream.CreateReader(); BinaryWriter bw; if (settings.ClearOutputHandling == 0) { outputConsoleString = null; // delete output from last execution outputConsoleString = new StringBuilder(); } else { outputConsoleString.AppendLine(); outputConsoleString.AppendLine(); } #endregion try { //GuiLogMessage("Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), NotificationLevel.Debug); // right //GuiLogMessage("Environment.CurrentDirectory " + path, NotificationLevel.Debug); // wrong // read from input stream and save as temporary file (which will later be passed to the SAT Solver) int bytesRead = 0; byte[] bytes = new byte[BUFFERSIZE]; using (bw = new BinaryWriter(File.Open(tempCnfFilename, FileMode.Create))) { while ((bytesRead = inputStream.ReadFully(bytes)) > 0) { bw.Write(bytes, 0, bytesRead); } } // build argument string string args = buildArgs(); solverProcess = new Process { StartInfo = new ProcessStartInfo { FileName = path + "\\" + solverExe, Arguments = args, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, } }; // DEBUG print args /* * string debug_args = ""; * if (args.Contains("-")) * { * debug_args = args.Substring(args.IndexOf("-"), args.Length - args.IndexOf("-")); * } * outputConsoleString.AppendLine("Arguments: " + debug_args); * outputConsoleStream = new CStreamWriter(); * outputConsoleStream.Write(encoding.GetBytes(outputConsoleString.ToString())); * outputConsoleStream.Close(); * OnPropertyChanged("OutputConsoleStream"); */ // attach event handler for process' data output solverProcess.OutputDataReceived += new DataReceivedEventHandler(ReadProcessOutput); solverProcess.Start(); ProgressChanged(1, 100); // begin asynchronous read solverProcess.BeginOutputReadLine(); solverProcess.WaitForExit(); exitcode = solverProcess.ExitCode; // action depends on exitcode and used solver (error handling / result output) if (exitcode != -1) { exitcodeHandling(exitcode); } else { GuiLogMessage("Solver returned without exitcode!", NotificationLevel.Warning); } outputResultStream.Close(); OnPropertyChanged("OutputResultStream"); } catch (Exception exception) { GuiLogMessage(exception.Message + "\r\n" + exception.StackTrace, NotificationLevel.Error); } finally { File.Delete(outputResultFilename); File.Delete(tempCnfFilename); } ProgressChanged(100, 100); }
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); } }
public void Execute() { try { // this is for localization ResourceManager resourceManager = new ResourceManager("Cryptool.RC4.Properties.Resources", GetType().Assembly); // make sure we have a valid data input if (inputData == null) { GuiLogMessage(resourceManager.GetString("ErrorInputDataNotProvided"), NotificationLevel.Error); return; } // make sure we have a valid key input if (inputKey == null) { GuiLogMessage(resourceManager.GetString("ErrorInputKeyNotProvided"), NotificationLevel.Error); return; } byte[] key = ToByteArray(inputKey); // make sure the input key is within the desired range if ((key.Length < 5 || key.Length > 256)) { GuiLogMessage(resourceManager.GetString("ErrorInputKeyInvalidLength"), NotificationLevel.Error); return; } // now execute the actual encryption using (CStreamReader reader = inputData.CreateReader()) { // create the output stream outputStreamWriter = new CStreamWriter(); // some variables int i = 0; int j = 0; // create the sbox byte[] sbox = new byte[256]; // initialize the sbox sequentially for (i = 0; i < 256; i++) { sbox[i] = (byte)(i); } // re-align the sbox (and incorporate the key) j = 0; for (i = 0; i < 256; i++) { j = (j + sbox[i] + key[i % key.Length]) % 256; byte sboxOld = sbox[i]; sbox[i] = sbox[j]; sbox[j] = sboxOld; } // process the input data using the modified sbox int position = 0; DateTime startTime = DateTime.Now; // some inits i = 0; j = 0; long bytesRead = 0; const long blockSize = 256; byte[] buffer = new byte[blockSize]; while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0 && !stop) { for (long n = 0; n < bytesRead; n++) { i = (i + 1) % 256; j = (j + sbox[i]) % 256; byte sboxOld = sbox[i]; sbox[i] = sbox[j]; sbox[j] = sboxOld; byte sboxRandom = sbox[(sbox[i] + sbox[j]) % 256]; byte cipherByte = (byte)(sboxRandom ^ buffer[n]); outputStreamWriter.WriteByte(cipherByte); } if ((int)(reader.Position * 100 / reader.Length) > position) { position = (int)(reader.Position * 100 / reader.Length); ProgressChanged(reader.Position, reader.Length); } } outputStreamWriter.Close(); // dump status information DateTime stopTime = DateTime.Now; TimeSpan duration = stopTime - startTime; 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"); } if (stop) { GuiLogMessage("Aborted!", NotificationLevel.Info); } } } catch (CryptographicException cryptographicException) { GuiLogMessage(cryptographicException.Message, NotificationLevel.Error); } catch (Exception exception) { GuiLogMessage(exception.Message, NotificationLevel.Error); } finally { ProgressChanged(1, 1); } }
/// <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; } }
/// <summary> /// Called every time this plugin is run in the workflow execution. /// </summary> public void Execute() { ProgressChanged(0, 1); try { inputStreamReader = InputStream.CreateReader(); //inputStreamReader.WaitEof(); if (!ValidateInputs()) { return; // beende die Ausführung bei Problemen mit den Eingabedaten } debugDataWriter = new CStreamWriter(); if (settings.Debug) { WriteDebug("Starting computation ...\r\n\r\n"); WriteDebug(String.Format("mode: {0}\r\n", settings.HashMode)); if (settings.HashMode != CypherMatrixHashSettings.CypherMatrixHashMode.Mini) { WriteDebug(String.Format("permutation: {0}\r\n", settings.Perm)); } else { WriteDebug("permutation: none\r\n"); } WriteDebug("\r\n\r\n"); } Stopwatch sw = new Stopwatch(); sw.Start(); Hash(); sw.Stop(); if (!stop) { GuiLogMessage(string.Format("Processed {0:N} KiB data in {1} ms.", (double)InputStream.Length / 1024, sw.ElapsedMilliseconds), NotificationLevel.Info); GuiLogMessage(string.Format("Achieved data throughput: {0:N} kB/s", (double)InputStream.Length / sw.ElapsedMilliseconds), NotificationLevel.Info); } } catch (Exception exception) { GuiLogMessage(exception.Message + "\r\n" + exception.StackTrace, NotificationLevel.Error); if (settings.Debug) { WriteDebug("\r\nThe following error occurred during execution:\r\n"); WriteDebug(exception.Message + "\r\n" + exception.StackTrace + "\r\n"); } } finally { if (stop) { GuiLogMessage("Computation aborted!", NotificationLevel.Warning); stop = false; } if (settings.Debug) { WriteDebug("\r\n>>>>>>>>>> END OF OPERATION <<<<<<<<<<"); } else { WriteDebug("You have to enable the debug logging to see the internal variables here."); } debugDataWriter.Flush(); debugDataWriter.Close(); OnPropertyChanged("OutputDebug"); } ProgressChanged(1, 1); }
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); } }