コード例 #1
0
        /// <summary>
        /// To read an existing file. Reads the Header
        /// </summary>
        /// <param name="Order"></param>
        /// <param name="Path"></param>
        /// <param name="createFixedSizeText"></param>
        public Tree(int Order, string Path, ICreateFixedSizeText <T> createFixedSizeText)
        {
            this.Order = Order;
            this.Path  = Path;
            this.createFixedSizeText = createFixedSizeText;

            var buffer = new byte[Header.FixedSize];

            using (var fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                fs.Seek(0, SeekOrigin.Begin);
                fs.Read(buffer, 0, Header.FixedSize);
            }

            var HeaderString = ByteGenerator.ConvertToString(buffer);
            var values       = HeaderString.Split(Util.Separator);

            this.Root         = Convert.ToInt16(values[0]);
            this.Order        = Convert.ToInt16(values[1]);
            this.LastPosition = Convert.ToInt16(values[2]);
        }
コード例 #2
0
ファイル: Algorithms.cs プロジェクト: ivan100sic/tpj-projekat
        public static uint[,] Decrypt(uint[,] matrix, string password)
        {
            int n = matrix.GetLength(0);
            int m = matrix.GetLength(1);

            uint[,] result = new uint[n, m];

            ByteGenerator g = new ByteGenerator(password);

            // xor
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    matrix[i, j] ^= g.nextUint24();
                }
            }

            // shift
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    int k = i, l = j + 1;
                    if (l == m)
                    {
                        l = 0;
                        k++;
                        if (k == n)
                        {
                            k = 0;
                        }
                    }
                    result[k, l] = matrix[i, j];
                }
            }

            return(result);
        }
コード例 #3
0
        public void SymmetricEncryptor_BasicUsage()
        {
            // Arrange
            int blockSize = 1000;

            byte[] buffer = new ByteGenerator().GenerateBytes(blockSize);
            string key    = "test key";

            byte[] decryptedBuffer;
            byte[] encryptedBuffer;

            using (SymmetricEncryptor encryptor = new SymmetricEncryptor())
            {
                //Encrypt
                encryptedBuffer = encryptor.EncryptBytes(buffer, key);

                // Decrypt
                decryptedBuffer = encryptor.DecryptBytes(encryptedBuffer, key);
            }             // IDispose - Closes and clears the keys in memory

            // Assert - Check to make sure the bytes are all the same
            Assert.IsTrue(buffer.SequenceEqual(decryptedBuffer));
        }
コード例 #4
0
ファイル: Node.cs プロジェクト: josue0ghost/Laboratorio2ED2
        internal Node <T> ReadNode(string Path, int Order, int Root, int Position, ICreateFixedSizeText <T> createFixedSizeText)
        {
            Node <T> node = new Node <T>(Order, Position, 0, createFixedSizeText);

            node.Data = new List <T>();

            int HeaderSize = Header.FixedSize;

            var buffer = new byte[node.FixedSize(node.Father)];

            using (var fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                fs.Seek((HeaderSize + ((Root - 1) * node.FixedSize(node.Father))), SeekOrigin.Begin);
                fs.Read(buffer, 0, node.FixedSize(node.Father));
            }

            var NodeString = ByteGenerator.ConvertToString(buffer);
            var Values     = NodeString.Split(Util.Separator);

            node.Father = Convert.ToInt32(Values[1]);

            //Hijos
            for (int i = 2; i < node.Children.Count + 2; i++)
            {
                node.Children[i] = Convert.ToInt32(Values[i]);
            }

            int DataLimit = node.Children.Count + 2;

            //Valores
            for (int i = DataLimit; i < node.Data.Count; i++)
            {
                node.Data[i] = createFixedSizeText.Create(Values[i]);
            }

            return(node);
        }
コード例 #5
0
        public void decode(Node root, ref int index, BitArray str, ref string result)
        {
            if (root == null)
            {
                return;
            }
            if (root.Left == null && root.Right == null)
            {
                byte[] toStr = { root.byt };
                result += ByteGenerator.ConvertToString(toStr);
                return;
            }

            index++;

            if (str[index] == false)
            {
                decode(root.Left, ref index, str, ref result);
            }
            else
            {
                decode(root.Right, ref index, str, ref result);
            }
        }
コード例 #6
0
        public async Task <IActionResult> DecompressFile([FromForm] IFormFile file)
        {
            try
            {
                // Escribir archivo subido hacia el servidor para trabajar con ese
                var path = _env.ContentRootPath;
                path = Path.Combine(path, "Files");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string pathInfo = Path.Combine(path, "Info");
                if (!Directory.Exists(pathInfo))
                {
                    Directory.CreateDirectory(pathInfo);
                }

                if (System.IO.File.Exists($"{pathInfo}/archivoCargado.txt"))
                {
                    System.IO.File.Delete($"{pathInfo}/archivoCargado.txt");
                }

                using var saver = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                await file.CopyToAsync(saver);

                saver.Close();

                // Leer el archivo en el servidor para trabajar sobre él
                using var fileWritten = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                using var reader      = new BinaryReader(fileWritten);
                var buffer = new byte[2000000];
                while (fileWritten.Position < fileWritten.Length)
                {
                    buffer = reader.ReadBytes(2000000);
                }
                reader.Close();
                fileWritten.Close();

                var nodeString = ByteGenerator.ConvertToString(buffer);

                Huffman huff = new Huffman();
                string  cadena_descifrada = huff.Descifrado(nodeString);


                // Buscar el nombre original en el archivo Historial.txt
                string pathHistorial = Path.Combine(pathInfo, "Historial.txt");
                if (!System.IO.File.Exists(pathHistorial))
                {
                    return(StatusCode(500, "Internal server error"));
                }
                string cadenaHistorial = System.IO.File.ReadAllText(pathHistorial);

                string[] cadenas        = cadenaHistorial.Split('/');
                string   nombreOriginal = "";

                foreach (var item in cadenas)
                {
                    if (item.Contains(file.FileName))
                    {
                        string[] valores = item.Split(';');
                        nombreOriginal = valores[0].Substring(0, valores[0].Length - 4);
                        break;
                    }
                }

                // Escribir el archivo {original}.txt en el servidor
                using (var fs = new FileStream($"{path}/{nombreOriginal}.txt", FileMode.OpenOrCreate))
                {
                    fs.Write(ByteGenerator.ConvertToBytes(cadena_descifrada), 0, cadena_descifrada.Length);
                }

                // Archivo a mandar de regreso
                //var fileStream = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                //return File(fileStream, "text/plain");

                return(Ok());
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Internal server error"));
            }
        }
コード例 #7
0
        public async Task <IActionResult> CompressFile([FromForm] IFormFile file, string name)
        {
            try
            {
                // Escribir archivo subido hacia el servidor para trabajar con ese
                var path = _env.ContentRootPath;
                path = Path.Combine(path, "Files");

                string pathInfo = Path.Combine(path, "Info");


                if (System.IO.File.Exists($"{pathInfo}/archivoCargado.txt"))
                {
                    System.IO.File.Delete($"{pathInfo}/archivoCargado.txt");
                }

                using var saver = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                await file.CopyToAsync(saver);

                saver.Close();


                // Leer el archivo en el servidor para trabajar sobre él
                using var fileWritten = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                using var reader      = new BinaryReader(fileWritten);
                var buffer = new byte[2000000];
                while (fileWritten.Position < fileWritten.Length)
                {
                    buffer = reader.ReadBytes(2000000);
                }
                reader.Close();
                fileWritten.Close();

                var nodeString = ByteGenerator.ConvertToString(buffer);

                Huffman huff           = new Huffman();
                string  cadena_cifrada = huff.Cifrado(nodeString);


                // Escribir el archivo {name}.huff en el servidor

                using (var fs = new FileStream($"{path}/{name}.huff", FileMode.OpenOrCreate))
                {
                    fs.Write(ByteGenerator.ConvertToBytes(cadena_cifrada), 0, cadena_cifrada.Length);
                }


                // Obtener la info de compresión
                CompressionInfo cInfo = new CompressionInfo();
                cInfo.originalName        = file.FileName;
                cInfo.compressedFilePath  = Path.Combine(path, $"{name}.huff");
                cInfo.compressionRatio    = Math.Round(Convert.ToDouble(cadena_cifrada.Length) / Convert.ToDouble(nodeString.Length), 2);
                cInfo.compressionFactor   = Math.Round(1 / cInfo.compressionRatio, 2);
                cInfo.reductionPercentage = Math.Round((1 - cInfo.compressionRatio) * 100, 2);


                // Escribir en el archivo Historial.txt
                string       pathHistorial   = Path.Combine(pathInfo, "Historial.txt");
                string       cadenaHistorial = System.IO.File.ReadAllText(pathHistorial);
                StreamWriter newfile         = new StreamWriter(pathHistorial);

                if (cadenaHistorial.Length != 0)
                {
                    newfile.Write(cadenaHistorial);
                    newfile.Write("/");
                }
                newfile.Write(cInfo.originalName + ";" + cInfo.compressedFilePath + ";" + (cInfo.compressionRatio).ToString() + ";" + (cInfo.compressionFactor).ToString() + ";" + (cInfo.reductionPercentage).ToString());

                newfile.Close();


                //Archivo a mandar de regreso
                //var fileStream = new FileStream($"{path}/{name}.huff", FileMode.OpenOrCreate);
                string mensaje = "Archivo comprimido exitosamente";
                return(Ok(new { mensaje }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Internal server error"));
            }
        }
コード例 #8
0
        public void DecodeFile(byte[] text, string newName, string name)
        {
            string txt = ByteGenerator.ConvertToString(text);

            string[] separadores = { "@@@" };
            string[] nodes       = txt.Split(separadores, StringSplitOptions.None);

            int start = (nodes.Length - 1) * 3;

            Dictionary <byte, int> freq = new Dictionary <byte, int>();

            for (int i = 0; i < nodes.Length - 1; i++)
            {
                string val = nodes[i];

                string character = "";
                string integer   = "";

                if (int.TryParse(val[0].ToString(), out _))
                {
                    character += val[0];
                    for (int j = 1; j < val.Length; j++)
                    {
                        integer += val[j];
                        start++;
                    }
                }
                else
                {
                    for (int j = 0; j < val.Length; j++)
                    {
                        if (!int.TryParse(val[j].ToString(), out _))
                        {
                            character += val[j];
                        }
                        else
                        {
                            integer += val[j];
                            start++;
                        }
                    }
                }

                byte[] bt;
                if (character == "NTR")
                {
                    bt = ByteGenerator.ConvertToBytes('\n'.ToString());
                }
                else if (character == "NDL")
                {
                    bt = ByteGenerator.ConvertToBytes('\r'.ToString());
                }
                else
                {
                    bt = ByteGenerator.ConvertToBytes(character.ToString());
                }
                start += character.Length;

                if (!freq.ContainsKey(bt[0]))
                {
                    freq.Add(bt[0], Convert.ToInt32(integer));
                }
            }

            BuildHuffman(freq);

            BitArray result  = ToBitArray(text.Skip(start).ToArray());
            int      index   = -1;
            string   decoded = "";

            while (index < result.Length - 1)
            {
                decode(this.root, ref index, result, ref decoded);
            }

            string basePath = string.Format(@"{0}Arboles\", AppContext.BaseDirectory);
            string fullPath = basePath + newName;

            using (StreamWriter sw = new StreamWriter(fullPath))
            {
                sw.Write(decoded);
            }
        }
コード例 #9
0
 public ByteValueGenerator()
 {
     ValueGenerator = new ByteGenerator(RandomValuesGenerator);
 }
コード例 #10
0
        // ---------------------------
        // ------- ULONG -------------
        // ---------------------------

        /// <summary>
        /// На основе генератора случайных байтов возвращает
        /// генератор ulong, который дает числа не больше заданного значения.
        /// </summary>
        private static Func <ulong, ulong> ___CreateNextULongInclusive(ByteGenerator byteGenerator)
        {
            return(delegate(ulong maxValue)
            {
                // maxvalue - IS INCLUSIVE.

                if (maxValue == 0)
                {
                    return 0;
                }

                ulong savedMaxValue = maxValue;

                int wholeBytes = 0;     // количество байт, которое можно ничтоже сумняшеся заполнять полностью
                int tailBits = 0;       // а вот эту штучку полностью нельзя

                // ON DEBUG
                // Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(maxValue)));

                // 10000000|100000000|       257[10]
                // 00101011|111111111|       X[10]

                while (maxValue > 0)
                {
                    ++tailBits;

                    if (tailBits == 8)
                    {
                        ++wholeBytes;
                        tailBits = 0;
                    }

                    maxValue >>= 1;
                }

REPEAT:

                byte[] buffer = new byte[8];
                byteGenerator(buffer);

                // Все старшие разряды,
                // идущие больше целого числа байтов,
                // должны быть занулены.

                for (int i = wholeBytes + 1; i < 8; i++)
                {
                    buffer[i] = 0;
                }

                if (wholeBytes < 8)
                {
                    if (tailBits > 0)
                    {
                        // tailbits = 1 --> mask = 00000001
                        // tailbits = 3 --> mask = 00000111

                        byte mask = 1;

                        for (int j = 1; j < tailBits; j++)
                        {
                            mask <<= 1;
                            mask += 1;
                        }

                        buffer[wholeBytes] &= mask;
                    }
                    else
                    {
                        buffer[wholeBytes] = 0;
                    }
                }

                ulong sampledValue = BitConverter.ToUInt64(buffer, 0);

                if (sampledValue >= savedMaxValue)
                {
                    goto REPEAT;
                }

                return sampledValue;
            });
        }