Exemple #1
0
 public void Dispose()
 {
     try
     {
         stop               = false;
         counter            = 0;
         lengthOfInputByte  = 0;
         lengthOfOutputByte = 0;
         inputByteKey       = null;
         iV         = null;
         outputByte = null;
         crc32      = null;
         key        = null;
         if (internalInputByteList != null)
         {
             internalInputByteList.Clear();
         }
         internalInputByteList = null;
         inputStream           = null;
         //if (outputByteList != null) { outputByteList.Clear(); }
         //outputByteList = null;
         outputStreamWriter = null;
         if (internalInputByteList != null)
         {
             internalInputByteList.Clear();
         }
         //internalInputByteList = null;
     }
     catch (Exception exc)
     {
         GuiLogMessage(exc.Message.ToString(), NotificationLevel.Error);
     }
     this.stop = false;
 }
Exemple #2
0
 public void Dispose()
 {
     if (inputData != null)
     {
         inputData = null;
     }
 }
Exemple #3
0
        public void SHATestMethod()
        {
            var pluginInstance = TestHelpers.GetPluginInstance("SHA");
            var scenario1      = new PluginTestScenario(pluginInstance, new[] { "InputData", ".SHAFunction" }, new[] { "OutputDataStream" });
            var scenario2      = new PluginTestScenario(pluginInstance, new[] { "InputData", ".SHAFunction" }, new[] { "OutputData" });

            object[] output;

            foreach (TestVector vector in testvectors)
            {
                output = scenario1.GetOutputs(new object[] { vector.input.ToStream(), vector.mode });
                Assert.AreEqual(vector.output.ToUpper(), output[0].ToHex(), "Unexpected value in test #" + vector.n + ".");
                output = scenario2.GetOutputs(new object[] { vector.input.ToStream(), vector.mode });
                Assert.AreEqual(vector.output.ToUpper(), output[0].ToHex(), "Unexpected value in test #" + vector.n + ".");
            }

            foreach (TestVector vector in testvectors_loop)
            {
                ICryptoolStream input = vector.input.ToStream();
                for (int i = 0; i < 100000; i++)
                {
                    input = (ICryptoolStream)scenario1.GetOutputs(new object[] { input, vector.mode })[0];
                }
                Assert.AreEqual(vector.output.ToUpper(), input.ToHex(), "Unexpected value in iteration test #" + vector.n + ".");
            }
        }
Exemple #4
0
 public void Dispose()
 {
     InputIV      = null;
     InputKey     = null;
     InputStream  = null;
     OutputStream = null;
 }
Exemple #5
0
 public void Dispose()
 {
     stop               = false;
     inputKey           = null;
     inputData          = null;
     outputStreamWriter = null;
 }
Exemple #6
0
        public void Dispose()
        {
            try
            {
                stop         = false;
                inputKey     = null;
                inputIV      = null;
                inputStream  = null;
                outputStream = null;

                if (p_crypto_stream_dec != null)
                {
                    p_crypto_stream_dec.Flush();
                    p_crypto_stream_dec.Close();
                    p_crypto_stream_dec = null;
                }

                if (p_crypto_stream_enc != null)
                {
                    p_crypto_stream_enc.Flush();
                    p_crypto_stream_enc.Close();
                    p_crypto_stream_enc = null;
                }
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }

            this.stop = false;
        }
Exemple #7
0
 public static byte[] ToByteArray(this ICryptoolStream stream)
 {
     if (stream == null)
     {
         return(new byte[0]);
     }
     return(stream.CreateReader().ToByteArray());
 }
Exemple #8
0
 public static string ToHex(this ICryptoolStream stream)
 {
     if (stream == null)
     {
         return("");
     }
     return(stream.ToByteArray().ToHex());
 }
Exemple #9
0
        private byte[] ToByteArray(ICryptoolStream icstr)
        {
            CStreamReader stream = icstr.CreateReader();

            stream.WaitEof();
            byte[] buffer = new byte[stream.Length];
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            stream.ReadFully(buffer);
            return(buffer);
        }
Exemple #10
0
 private string Stream2Base64(ICryptoolStream value)
 {
     using (CStreamReader reader = value.CreateReader())
     {
         reader.WaitEof();
         byte[] byteValues = new byte[reader.Length];
         reader.Read(byteValues, 0, (int)reader.Length);
         return(Convert.ToBase64String(byteValues));
     }
 }
Exemple #11
0
        public void TestEmpty()
        {
            ICryptoolStream empty = CStreamWriter.Empty;

            CStreamReader reader = empty.CreateReader();

            byte[] buf  = new byte[1024];
            int    read = reader.ReadFully(buf);

            Assert.AreEqual(0, read);
        }
Exemple #12
0
 /// <summary>
 /// Called once when workflow execution starts.
 /// </summary>
 public void PreExecution()
 {
     inputImage = null;
     orgImg     = null;
     step1Img   = null;
     step2Img   = null;
     step4Img   = null;
     step6Bmp   = null;
     outputHash = null;
     isRunning  = true;
 }
Exemple #13
0
        /// <summary>
        /// Assigns a data source and initializes the algorithm, putting it into "initialized" state
        /// </summary>
        /// <param name="cStream">Data source</param>
        public void Initialize(ICryptoolStream cStream)
        {
            DataStream = cStream.CreateReader();

            SetUninitializedState();
            PerformInitializationStep();

            IsInitialized = true;

            OnStatusChanged();
        }
Exemple #14
0
 private string Stream2Hex(ICryptoolStream value)
 {
     using (CStreamReader reader = value.CreateReader())
     {
         int           byteValue;
         StringBuilder sb = new StringBuilder();
         while ((byteValue = reader.ReadByte()) != -1)
         {
             sb.Append(byteValue.ToString("x2"));
         }
         return(sb.ToString());
     }
 }
Exemple #15
0
        public static byte[] StreamToByteArray(ICryptoolStream stream)
        {
            byte[] buf = new byte[stream.Length];

            CStreamReader reader = stream.CreateReader();

            reader.WaitEof();
            reader.Seek(0, System.IO.SeekOrigin.Begin);
            reader.ReadFully(buf);
            reader.Close();

            return(buf);
        }
Exemple #16
0
 private string Stream2Text(ICryptoolStream value)
 {
     using (CStreamReader reader = value.CreateReader())
     {
         int           byteValue;
         StringBuilder sb = new StringBuilder();
         while ((byteValue = reader.ReadByte()) != -1)
         {
             // FIXME: UTF-8 characters may consist of more than a single byte
             sb.Append(System.Convert.ToChar(byteValue));
         }
         return(sb.ToString());
     }
 }
Exemple #17
0
 public void PreExecution()
 {
     _data   = null;
     _stream = null;
     _presentation.Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback) delegate
     {
         try
         {
             _presentation.Picture.Source = null;
         }
         catch (Exception ex)
         {
             GuiLogMessage("Could not clear picture in PreExecute: " + ex.Message, NotificationLevel.Error);
         }
     }, null);
 }
Exemple #18
0
        // convert stream to ulong
        private ulong stream2ulong(ICryptoolStream s)
        {
            byte[] tmpbuf = s.ToByteArray();
            Array.Reverse(tmpbuf);

            byte[] buf = new byte[8];
            for (int i = 0; i < 8; i++)
            {
                buf[i] = 0;
            }
            for (int i = 0; i < tmpbuf.Length; i++)
            {
                buf[i] = tmpbuf[i];
            }

            return(BitConverter.ToUInt64(buf, 0));
        }
Exemple #19
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);
        }
Exemple #20
0
        private byte[] ConvertStreamToByteArray(ICryptoolStream stream)
        {
            CStreamReader reader = stream.CreateReader();

            reader.WaitEof(); // does not support chunked streaming

            if (reader.Length > settings.MaxLength)
            {
                AddMessage("WARNING - Stream is too large (" + (reader.Length / 1024).ToString("0.00") + " kB), output will be truncated to " + (settings.MaxLength / 1024).ToString("0.00") + "kB", NotificationLevel.Warning);
            }

            byte[] byteArray = new byte[Math.Min(settings.MaxLength, reader.Length)];
            reader.Seek(0, SeekOrigin.Begin);
            reader.ReadFully(byteArray, 0, byteArray.Length);
            reader.Close();

            return(byteArray);
        }
Exemple #21
0
 public void SetContent(ICryptoolStream stream)
 {
     Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
     {
         try
         {
             using (CStreamReader reader = stream.CreateReader())
             {
                 FlowDocument flowDocumentNew = (FlowDocument)XamlReader.Load(reader);
                 documentReader.Document      = flowDocumentNew;
             }
         }
         catch (Exception)
         {
             documentReader.Document = null;
         }
     }, documentReader);
 }
Exemple #22
0
        private string returnStreamContent(ICryptoolStream stream)
        {
            string res = "";

            if (stream == null)
            {
                return(null);
            }

            using (CStreamReader reader = stream.CreateReader())
            {
                res = Encoding.Default.GetString(reader.ReadFully());


                if (res.Length == 0)
                {
                    return(null);
                }
            }

            return(res);
        }
Exemple #23
0
        public void Dispose()
        {
            try
            {
                stop               = false;
                inputKey           = null;
                inputIV            = null;
                inputStream        = null;
                outputStreamWriter = null;

                if (p_crypto_stream != null)
                {
                    p_crypto_stream.Flush();
                    p_crypto_stream.Clear();
                    p_crypto_stream = null;
                }
            }
            catch (Exception ex)
            {
                GuiLogMessage(ex.Message, NotificationLevel.Error);
            }
            this.stop = false;
        }
Exemple #24
0
 public void PostExecution()
 {
     inputData = null;
 }
Exemple #25
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);
                }
            }
        }
Exemple #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 = 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);
            }
        }
Exemple #27
0
 public void PreExecution()
 {
     inputData = null;
 }
Exemple #28
0
        /// <summary>
        /// HOWTO: Enter the algorithm you'd like to implement in this method.
        /// </summary>
        public void Execute()
        {
            int matrixSize;

            switch (settings.MatrixSize)
            {
            case 0:
                matrixSize = 5;
                break;

            case 1:
                matrixSize = 6;
                break;

            default:
                matrixSize = 5;
                break;
            }

            // HOWTO: Use this to show the progress of a plugin algorithm execution in the editor.
            ProgressChanged(0, 1);

            // HOWTO: After you have changed an output property, make sure you announce the name of the changed property to the CT2 core.

            //OnPropertyChanged("Difference");

            // HOWTO: You can pass error, warning, info or debug messages to the CT2 main window.

            GuiLogMessage("Text Corpus File: " + settings.TextCorpusFile, NotificationLevel.Info);


            if ((settings.Alphabet.Contains(settings.Separator)) && (settings.Alphabet.Contains(settings.SeparatorReplacement)) &&
                (settings.Alphabet.Contains(settings.ReplacementChar)))
            {
                if (!ContainsDuplicates(settings.Alphabet))
                {
                    if (settings.TextCorpusFile != null && settings.TextCorpusFile.EndsWith(".txt"))
                    {
                        if (((matrixSize == 5) && (settings.Alphabet.Length == 25)) ||
                            ((matrixSize == 6) && (settings.Alphabet.Length == 36)))
                        {
                            unformattedTextByte = System.IO.File.ReadAllBytes(settings.TextCorpusFile);
                            unformattedText     = Encoding.Default.GetString(unformattedTextByte);

                            GuiLogMessage(settings.Alphabet, NotificationLevel.Info);

                            SortAlphabet(settings.Alphabet);
                            GuiLogMessage("sortedAlphabet: " + sortedAlphabet, NotificationLevel.Info);
                            GuiLogMessage("ToUpper: " + Convert.ToString(settings.CorpusToUpper), NotificationLevel.Info);

                            FormatText();

                            GuiLogMessage("formatted text: " + formattedText, NotificationLevel.Info);

                            CalcLogStat();


                            // Write Alphabet Length, sortedAlphabet and logStat (double array) in logStatByte (byte array)
                            logStatByte = new byte[(8 * logStat.Length) + 1 + sortedAlphabet.Length];
                            byte[] doubleValue = new byte[8];
                            int    index       = 0;

                            logStatByte[index] = (byte)sortedAlphabet.Length;
                            index++;

                            for (int i = 0; i < sortedAlphabet.Length; i++)
                            {
                                logStatByte[index] = Convert.ToByte(sortedAlphabet[i]);
                                index++;
                            }

                            for (int i = 0; i < (int)Math.Pow(matrixSize, 2); i++)
                            {
                                for (int j = 0; j < (int)Math.Pow(matrixSize, 2); j++)
                                {
                                    doubleValue = BitConverter.GetBytes(logStat[i, j]);
                                    for (int k = 0; k < 8; k++)
                                    {
                                        logStatByte[index] = doubleValue[k];
                                        index++;
                                    }
                                }
                            }


                            csBigraphStatistic = new CStreamWriter(logStatByte);
                            OnPropertyChanged("OutputStream");


                            GuiLogMessage("CalcLogStat completed: ", NotificationLevel.Info);
                        }

                        else
                        {
                            System.Windows.MessageBox.Show("Wrong Alphabet Length!\nAlphabet must contain " + Convert.ToString(Math.Pow(matrixSize, 2)) + " characters.");
                        }
                    }
                    else if (settings.TextCorpusFile == null)
                    {
                        System.Windows.MessageBox.Show("For calculating the bigraph statistic a text corpus file is needed!");
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("Text Corpus File has to be a .txt file!");
                        settings.TextCorpusFile = null;
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Alphabet contains duplicate characters!");
                }
            }

            else
            {
                System.Windows.MessageBox.Show("Alphabet must contain Separator, Separator Replacement and Replacement Character!");
            }

            ProgressChanged(1, 1);
        }
Exemple #29
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);
            }
        }
Exemple #30
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);
            }
        }