Exemplo n.º 1
0
        public void Execute()
        {
            ProgressChanged(0.5, 1.0);
            if (inputData != null)
            {
                if (Presentation.IsVisible)
                {
                    md5.Initialize(inputData);
                }
                else
                {
                    HashAlgorithm builtinMd5 = System.Security.Cryptography.MD5.Create();

                    using (CStreamReader reader = inputData.CreateReader())
                    {
                        OutputData = builtinMd5.ComputeHash(reader);
                    }

                    ProgressChanged(1.0, 1.0);
                }
            }
            else
            {
                GuiLogMessage("Received null value for CryptoolStream.", NotificationLevel.Warning);
            }
        }
Exemplo n.º 2
0
        public void Execute()
        {
            Progress(0.5, 1.0);

            if (inputData != null && inputData.Length >= 0)
            {
                System.Security.Cryptography.RIPEMD160 ripeMd160Hash = System.Security.Cryptography.RIPEMD160.Create();
                using (CStreamReader reader = inputData.CreateReader())
                {
                    OutputData = ripeMd160Hash.ComputeHash(reader);
                }

                GuiLogMessage("Hash created.", NotificationLevel.Info);
                Progress(1, 1);
            }
            else
            {
                if (inputData == null)
                {
                    GuiLogMessage("Received null value for CryptoolStream.", NotificationLevel.Warning);
                }
                else
                {
                    GuiLogMessage("No input stream.", NotificationLevel.Warning);
                }
            }

            Progress(1.0, 1.0);
        }
Exemplo n.º 3
0
 public static byte[] ToByteArray(this ICryptoolStream stream)
 {
     if (stream == null)
     {
         return(new byte[0]);
     }
     return(stream.CreateReader().ToByteArray());
 }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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));
     }
 }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
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();
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
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());
     }
 }
Exemplo n.º 10
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());
     }
 }
Exemplo n.º 11
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            System.Security.Cryptography.HMAC hmacAlgorithm;

            switch ((HMACSettings.HashFunction)settings.SelectedHashFunction)
            {
            case HMACSettings.HashFunction.MD5:
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;

            case HMACSettings.HashFunction.RIPEMD160:
                hmacAlgorithm = new System.Security.Cryptography.HMACRIPEMD160();
                break;

            case HMACSettings.HashFunction.SHA1:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA1();
                break;

            case HMACSettings.HashFunction.SHA256:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA256();
                break;

            case HMACSettings.HashFunction.SHA384:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA384();
                break;

            case HMACSettings.HashFunction.SHA512:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA512();
                break;

            default:
                GuiLogMessage("No hash algorithm for HMAC selected, using MD5.", NotificationLevel.Warning);
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;
            }

            hmacAlgorithm.Key = key;

            OutputData = (inputData != null) ? hmacAlgorithm.ComputeHash(inputData.CreateReader()) : hmacAlgorithm.ComputeHash(new byte[] {});

            GuiLogMessage(String.Format("HMAC computed. (using hash algorithm {0}: {1})", settings.SelectedHashFunction, hmacAlgorithm.GetType().Name), NotificationLevel.Info);

            ProgressChanged(1, 1);
        }
Exemplo n.º 12
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);
 }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        public void Execute()
        {
            try
            {
                ProgressChanged(0, 0);
                if (_data == null && _stream == null)
                {
                    return;
                }

                if (_stream != null)
                {
                    var reader = _stream.CreateReader();
                    _data = reader.ReadFully();
                }

                _presentation.Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback) delegate
                {
                    try{
                        var decoder = BitmapDecoder.Create(new MemoryStream(_data),
                                                           BitmapCreateOptions.PreservePixelFormat,
                                                           BitmapCacheOption.None);

                        if (decoder.Frames.Count > 0)
                        {
                            _presentation.Picture.Source = decoder.Frames[0];
                        }
                    }
                    catch (Exception ex)
                    {
                        GuiLogMessage("Could not display picture: " + ex.Message, NotificationLevel.Error);
                        return;
                    }
                }, null);
                ProgressChanged(1, 1);
            }
            catch (Exception ex)
            {
                GuiLogMessage("Could not display picture: " + ex.Message, NotificationLevel.Error);
            }
        }
Exemplo n.º 15
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);
        }
Exemplo n.º 16
0
        public void Execute()
        {
            Progress(0.5, 1.0);

            HashAlgorithm hash = GetHashAlgorithm(settings.SHAFunction);

            if (inputData == null)
            {
                GuiLogMessage("Received null value for ICryptoolStream.", NotificationLevel.Warning);
            }
            else if (hash == null)
            {
                GuiLogMessage("No valid SHA algorithm instance.", NotificationLevel.Error);
            }
            else
            {
                using (CStreamReader reader = inputData.CreateReader())
                {
                    OutputData = hash.ComputeHash(reader);
                    //GuiLogMessage("Hash created.", NotificationLevel.Info);
                }
            }
            Progress(1.0, 1.0);
        }
Exemplo n.º 17
0
 private byte[] ICryptoolStreamToByteArray(ICryptoolStream stream)
 {
     return(CStreamReaderToByteArray(stream.CreateReader()));
 }
Exemplo n.º 18
0
        public void Execute()
        {
            if (inputStream == null || inputStream.Length == 0)
            {
                return;
            }

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

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

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

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

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

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

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

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

                            lengthOfInputByte  += 4;
                            lengthOfOutputByte += 4;

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

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

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

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

                            outputByte = RC4.rc4encrypt(tempInputByte, key);

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

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

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

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

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


                            iEEEHeaderInformation = removeWEPParameters(iEEEHeaderInformation);

                            lengthOfInputByte = lengthOfOutputByte = tempInputByte.Length;

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

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

                            outputByte = RC4.rc4encrypt(tempInputByte, key);

                            outputByte = removeICV(tempInputByte);

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

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

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

                        default:
                            break;
                        }
                        counter++;
                        if (this.internalInputByteList != null)
                        {
                            ProgressChanged(counter, internalInputByteList.Count);
                        }
                        tempInputByte = null;
                    }
                    DateTime stopTime = DateTime.Now;
                    TimeSpan duration = stopTime - startTime;
                    if (!stop)
                    {
                        if (settings.Action == 0)
                        {
                            GuiLogMessage("Encryption complete!", NotificationLevel.Info);
                        }
                        if (settings.Action == 1)
                        {
                            GuiLogMessage("Decryption complete!", NotificationLevel.Info);
                        }
                        if (counter == 1)
                        {
                            GuiLogMessage("Time used [h:min:sec]: " + duration.ToString(), NotificationLevel.Info);
                        }
                        else
                        {
                            GuiLogMessage("Time used [h:min:sec]: " + duration.ToString() + " for " + counter.ToString("#,#", CultureInfo.InstalledUICulture) + " packets.", NotificationLevel.Info);
                        }
                        outputStreamWriter.Close();
                        OnPropertyChanged("OutputStream");
                    }
                    if (stop)
                    {
                        outputStreamWriter.Close();
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                    internalInputByteList.Clear();
                    internalInputByteList = null;
                    key = null;
                }
            }
            catch (Exception exc)
            {
                GuiLogMessage(exc.Message.ToString(), NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1.0, 1.0);
            }
        }
Exemplo n.º 19
0
        private void process(int action)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (InputStream == null || InputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

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

                ConfigureAlg(p_alg);

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

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

                outputStreamWriter = new CStreamWriter();

                ICryptoolStream inputdata = InputStream;

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

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

                DateTime startTime = DateTime.Now;

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

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

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

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

                    int validBytes = (int)inputdata.Length;

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

                    encrypt.Dispose();
                    outputStreamWriter.Write(outputData, 0, validBytes);
                    inbytes = inputdata.Length;
                }
                else
                {
                    // 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 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;

                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);
            }
        }
Exemplo n.º 20
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);
            }
        }
Exemplo n.º 21
0
        public void Execute()
        {
            ProgressChanged(0, 1);


            deleteDataFile();


            minimumDataAmount.Clear();
            fillDataDic();

            // this block is reading the CStream and writing the data into a file.
            // probably this is the biggest lack of performance.
            // the C# Class is reading a stream and writing it onto another FileStream so the DLL can read it ...
            ProgressChanged(0.2, 1);
            using (CStreamReader reader = dataAsStream.CreateReader())
            {
                reader.WaitEof();
                if ((int)reader.Length < (minimumDataAmount[selected] * 4))
                {
                    GuiLogMessage("More data is needed to execute this test properly. \nThe minimum amount of numbers required for this Test is: " + (minimumDataAmount[selected]), NotificationLevel.Info);
                    Result  = "More data is needed to execute this test properly. \nThe minimum amount of numbers required for this Test is: " + (minimumDataAmount[selected]);
                    Success = false;
                    OnPropertyChanged("Result");
                    OnPropertyChanged("Success");
                    ProgressChanged(1, 1);

                    //fileStream = null;
                    return;
                }
                int    bytesRead;
                byte[] buffer = new byte[4];

                while ((bytesRead = reader.Read(buffer)) > 0)
                {
                    // Note: buffer can contain less data than buffer.Length, therefore consider bytesRead
                    writeData(buffer, bytesRead);
                }
            }
            ProgressChanged(0.5, 1);
            //fileStream.Close();


            // The execution of the DLL methods documented above
            initializeTest_types();
            set_globals();
            // but this time the generator must be 200 ( File input Generator to read the written file )
            set_generator(200);
            choose_rng();



            // singleTest case
            if (selected != 999)
            {
                // sets the testNumber correctly to execute the requested test
                set_DtestNum(selected);
                // sets the fasterFactor (explanation to this factor will come in the docu)
                // at least the fasterFactor is shorten the needed amount of numbers.
                //setFasterFactor(settings.FasterFactor+1);
                setNTuple(settings.NTuple);
                run_tests();
                //GuiLogMessage("Just one test will be executed", NotificationLevel.Info);
            }
            // alltest case
            else
            {
                set_ALL(1);
                //setFasterFactor(settings.FasterFactor + 1);
                setNTuple(settings.NTuple);
                run_tests();
                //GuiLogMessage("All the tests will be executed", NotificationLevel.Info);
            }

            int passed = get_passed();

            switch (passed)
            {
            case 1:
                Result  = "The data PASSED this test on randomness";
                Success = true;
                break;

            case 0:
                Result  = "The data is WEAK according to its randomness";
                Success = true;
                break;

            case -1:
                Result  = "The data FAILED on this test on randomness";
                Success = false;
                break;

            default:
                Result  = "Something went wrong";
                Success = false;
                break;
            }

            reachedEOF = get_EOF();
            if (reachedEOF == 1)
            {
                GuiLogMessage("More data is needed to execute this test properly. \nHave a look at the tool description to get information about the minimum data needed for each test", NotificationLevel.Info);
                Result  = "More data is needed to execute this test properly. \nHave a look at the tool description to get information about the minimum data needed for each test";
                Success = false;
            }

            OnPropertyChanged("Result");
            OnPropertyChanged("Success");

            ProgressChanged(1, 1);

            //fileStream.Dispose();
            //fileStream.Close();
            //fileStream = null;
        }
Exemplo n.º 22
0
        private void process(int action, int padding)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (inputStream == null || inputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

                outputStreamWriter = new CStreamWriter();

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

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

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

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

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

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

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

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

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

                    uint[] vector = new uint[2];

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

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

                            vector = general_test(vector, key, 0);

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

                            vector = general_test(vector, key, 1);

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

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

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

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

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

            /*catch (CryptographicException cryptographicException)
             * {
             *  // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
             *  // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
             *  // the error messages will be doubled.
             *  // As a workaround we set p_crypto_stream to null here.
             *  p_crypto_stream = null;
             *  //GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
             * }*/
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Exemplo n.º 23
0
        private void process(int action, int padding)
        {
            //Encrypt/Decrypt Stream
            try
            {
                if (InputStream == null || InputStream.Length == 0)
                {
                    GuiLogMessage("No input data, aborting now", NotificationLevel.Error);
                    return;
                }

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

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

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

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

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

                DateTime startTime = DateTime.Now;

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

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

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

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

                CStreamReader reader = inputdata.CreateReader();

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

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

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

                outputStream.Close();

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

                if (!stop)
                {
                    GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                    OnPropertyChanged("OutputStream");
                }
                else
                {
                    GuiLogMessage("Aborted!", NotificationLevel.Info);
                }
            }
            catch (Exception exception)
            {
                GuiLogMessage(exception.Message, NotificationLevel.Error);
            }
            finally
            {
                ProgressChanged(1, 1);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Called every time this plugin is run in the workflow execution.
        /// </summary>
        public void Execute()
        {
            int       progress = 1;
            const int STEPS    = 10;

            // An imagesize under 4x4 does not make any sense
            // Sizes above 128x128 get to slow
            if (settings.Size < 4)
            {
                settings.Size = 4;
                GuiLogMessage(Resources.ToSmallWarning, NotificationLevel.Warning);
            }
            else if (settings.Size > 128)
            {
                settings.Size = 128;
                GuiLogMessage(Resources.ToBigWarning, NotificationLevel.Warning);
            }
            else
            {
                int  size      = settings.Size;
                bool wrongSize = true;
                int  max       = 1;
                // Check if the input size is a power of two
                for (int i = 4; i <= 1024; i *= 2)
                {
                    if (size == i)
                    {
                        wrongSize = false;
                        break;
                    }
                    else if (size < i)
                    {
                        max = i;
                        break;
                    }
                }

                int j = max / 2;
                // If the input size is not a power of two, set it to the nearest power of two
                if (wrongSize)
                {
                    int middle = (max - j) / 2;
                    if (size <= j + middle)
                    {
                        size = j;
                    }
                    else
                    {
                        size = max;
                    }
                    settings.Size = size;
                    GuiLogMessage(Resources.PowerOfTwoWarning + " " + size + "x" + size + ".", NotificationLevel.Warning);
                }
            }
            OnPropertyChanged("size");

            ProgressChanged(0, 1);

            if (InputImage == null)
            {
                GuiLogMessage(Resources.NoImageError, NotificationLevel.Error);
                return;
            }

            using (CStreamReader reader = inputImage.CreateReader())
            {
                using (Bitmap bitmap = new Bitmap(reader))
                {
                    // Original Image:
                    orgImg = new Image <Bgr, Byte>(bitmap);
                    if ((settings.PresentationStep > 1 && settings.ShowEachStep) || (settings.PresentationStep == 1))
                    {
                        CreateOutputStream(bitmap);
                        OnPropertyChanged("OutputImage");
                    }
                    // Step 1: Gray scale
                    step1Img = orgImg.Convert <Gray, byte>().Convert <Gray, double>();
                    ProgressChanged(progress++, STEPS);
                    if ((settings.PresentationStep > 2 && settings.ShowEachStep) || (settings.PresentationStep == 2))
                    {
                        CreateOutputStream(step1Img.ToBitmap());
                        OnPropertyChanged("OutputImage");
                    }
                    ProgressChanged(progress++, STEPS);

                    // Step 2: Resize to sizexsize (standard: 16x16)
                    int size     = settings.Size; // standard: 16
                    int halfSize = size / 2;      // standard: 8
                    step2Img = step1Img.Resize(size, size, Emgu.CV.CvEnum.INTER.CV_INTER_NN);
                    ProgressChanged(progress++, STEPS);
                    if ((settings.PresentationStep > 3 && settings.ShowEachStep) || (settings.PresentationStep == 3))
                    {
                        CreateOutputStream(step2Img.ToBitmap());
                        OnPropertyChanged("OutputImage");
                    }
                    ProgressChanged(progress++, STEPS);

                    // Step 3: Find brightest quarter
                    float[] subImage = new float[4];
                    for (int i = 0; i < step2Img.Width && isRunning; i++)
                    {
                        for (int j = 0; j < step2Img.Height && isRunning; j++)
                        {
                            if ((i < halfSize) && (j < halfSize))
                            {
                                subImage[0] += step2Img.ToBitmap().GetPixel(i, j).GetBrightness();
                            }
                            else if ((i >= halfSize) && (j < halfSize))
                            {
                                subImage[1] += step2Img.ToBitmap().GetPixel(i, j).GetBrightness();
                            }
                            else if ((i < halfSize) && (j >= halfSize))
                            {
                                subImage[2] += step2Img.ToBitmap().GetPixel(i, j).GetBrightness();
                            }
                            else if ((i >= halfSize) && (j >= halfSize))
                            {
                                subImage[3] += step2Img.ToBitmap().GetPixel(i, j).GetBrightness();
                            }
                        }
                    }

                    float maxValue = subImage.Max();
                    int   flip     = subImage.ToList().IndexOf(maxValue);
                    ProgressChanged(progress++, STEPS);

                    // Step 4: Flip brightest quarter to left upper corner
                    step4Img = step2Img;
                    switch (flip)
                    {
                    case 1:
                        step4Img = step4Img.Flip(Emgu.CV.CvEnum.FLIP.HORIZONTAL);
                        subImage = swap(subImage, 1);
                        break;

                    case 2:
                        step4Img = step4Img.Flip(Emgu.CV.CvEnum.FLIP.VERTICAL);
                        subImage = swap(subImage, 2);
                        break;

                    case 3:
                        step4Img = step4Img.Flip(Emgu.CV.CvEnum.FLIP.HORIZONTAL);
                        step4Img = step4Img.Flip(Emgu.CV.CvEnum.FLIP.VERTICAL);
                        subImage = swap(subImage, 3);
                        break;
                    }

                    ProgressChanged(progress++, STEPS);
                    if ((settings.PresentationStep > 4 && settings.ShowEachStep) || (settings.PresentationStep == 4))
                    {
                        CreateOutputStream(step4Img.ToBitmap());
                        OnPropertyChanged("OutputImage");
                    }
                    ProgressChanged(progress++, STEPS);

                    // Step 5: Find median
                    float[] median = new float[4];
                    for (int i = 0; i < median.Length; i++)
                    {
                        median[i] = subImage[i] / ((size * size) / median.Length);
                    }
                    ProgressChanged(progress++, STEPS);

                    // Step 6: Set Brightness to 0 or 1, if above or under median
                    Bitmap step4Bmp = step4Img.ToBitmap();
                    step6Bmp = new Bitmap(step4Img.Width, step4Img.Height);
                    Boolean[][] b = new Boolean[4][];
                    for (int i = 0; i < b.Length; i++)
                    {
                        b[i] = new Boolean[(size * size) / median.Length];
                    }
                    for (int i = 0; i < step4Bmp.Width && isRunning; i++)
                    {
                        for (int j = 0; j < step4Bmp.Height && isRunning; j++)
                        {
                            if ((i < halfSize) && (j < halfSize))
                            {
                                float brightness = step4Bmp.GetPixel(i, j).GetBrightness();
                                if (brightness >= median[0])
                                {
                                    step6Bmp.SetPixel(i, j, Color.White);
                                    b[0][i * halfSize + j] = false;
                                }
                                else
                                {
                                    step6Bmp.SetPixel(i, j, Color.Black);
                                    b[0][i * halfSize + j] = true;
                                }
                            }
                            else if ((i >= halfSize) && (j < halfSize))
                            {
                                float brightness = step4Bmp.GetPixel(i, j).GetBrightness();
                                if (brightness >= median[1])
                                {
                                    step6Bmp.SetPixel(i, j, Color.White);
                                    b[1][(i - halfSize) * halfSize + j] = false;
                                }
                                else
                                {
                                    step6Bmp.SetPixel(i, j, Color.Black);
                                    b[1][(i - halfSize) * halfSize + j] = true;
                                }
                            }
                            else if ((i < halfSize) && (j >= halfSize))
                            {
                                float brightness = step4Bmp.GetPixel(i, j).GetBrightness();
                                if (brightness >= median[2])
                                {
                                    step6Bmp.SetPixel(i, j, Color.White);
                                    b[2][i * halfSize + (j - halfSize)] = false;
                                }
                                else
                                {
                                    step6Bmp.SetPixel(i, j, Color.Black);
                                    b[2][i * halfSize + (j - halfSize)] = true;
                                }
                            }
                            else if ((i >= halfSize) && (j >= halfSize))
                            {
                                float brightness = step4Bmp.GetPixel(i, j).GetBrightness();
                                if (brightness >= median[3])
                                {
                                    step6Bmp.SetPixel(i, j, Color.White);
                                    b[3][(i - halfSize) * halfSize + (j - halfSize)] = false;
                                }
                                else
                                {
                                    step6Bmp.SetPixel(i, j, Color.Black);
                                    b[3][(i - halfSize) * halfSize + (j - halfSize)] = true;
                                }
                            }
                        }
                    }

                    ProgressChanged(progress++, STEPS);
                    if (settings.PresentationStep == 5)
                    {
                        CreateOutputStream(step6Bmp);
                        OnPropertyChanged("OutputImage");
                    }
                    ProgressChanged(progress++, STEPS);

                    // Step 7: Calculate the hash
                    bool[] bools = new bool[b.Length * b[0].Length];
                    for (int i = 0; i < b.Length && isRunning; i++)
                    {
                        for (int j = 0; j < b[i].Length && isRunning; j++)
                        {
                            bools[i * b[i].Length + j] = b[i][j];
                        }
                    }

                    byte[] byteArray = new byte[bools.Length / 8];
                    int    bitIndex = 0, byteIndex = 0;
                    for (int i = 0; i < bools.Length && isRunning; i++)
                    {
                        if (bools[i])
                        {
                            byteArray[byteIndex] |= (byte)(((byte)1) << bitIndex);
                        }
                        bitIndex++;
                        if (bitIndex == 8)
                        {
                            bitIndex = 0;
                            byteIndex++;
                        }
                    }
                    OutputHash = byteArray;
                    OnPropertyChanged("OutputHash");
                }
            }
            ProgressChanged(1, 1);
        }
Exemplo n.º 25
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);
            }
        }
Exemplo n.º 26
0
        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);
            }
        }
Exemplo n.º 27
0
        public void Encrypt()
        {
            if (this.inputStream != null)
            {
                // Encrypt Stream
                try
                {
                    SymmetricAlgorithm p_alg = new PresentManaged();
                    ConfigureAlg(p_alg, true);

                    ICryptoolStream inputdata = InputStream;

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

                    CStreamReader reader = inputdata.CreateReader();

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

                    ICryptoTransform p_encryptor = p_alg.CreateEncryptor();

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

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

                    outputStream.Close();

                    if (!stop)
                    {
                        GuiLogMessage("Encryption complete! (in: " + inputStream.Length.ToString() + " bytes, out: " + outputStream.Length.ToString() + " bytes)", NotificationLevel.Info);
                        GuiLogMessage("Time used: " + duration.ToString(), NotificationLevel.Debug);
                        OnPropertyChanged("OutputStream");
                    }
                    else
                    {
                        GuiLogMessage("Aborted!", NotificationLevel.Info);
                    }
                }
                catch (CryptographicException cryptographicException)
                {
                    // TODO: For an unknown reason p_crypto_stream can not be closed after exception.
                    // Trying so makes p_crypto_stream throw the same exception again. So in Dispose
                    // the error messages will be doubled.
                    // As a workaround we set p_crypto_stream to null here.
                    p_crypto_stream_enc = null;
                    GuiLogMessage(cryptographicException.Message, NotificationLevel.Error);
                }
                catch (Exception exception)
                {
                    GuiLogMessage(exception.Message, NotificationLevel.Error);
                }
                finally
                {
                    Progress(1, 1);
                }
            }
        }
Exemplo n.º 28
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);
                }
            }
        }
Exemplo n.º 29
0
        /// <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();
        }