Ejemplo n.º 1
0
        public ActionResult Login(string username, string password)
        {
            SDES cipher = new SDES();

            bool correcto = false;
            var  personas = obtenerPersonas();

            foreach (var item in personas)
            {
                if (item.username == username && item.password == cipher.CifrarTexto(password, password.Length))
                {
                    correcto = true;
                    break;
                }
            }

            if (correcto)
            {
                string strUrl = String.Format("https://localhost:44316/api/token");

                string postUrl = $"{strUrl}/?username={username}&password={password}";

                WebRequest requestObjPost = WebRequest.Create(postUrl);
                requestObjPost.Method      = "POST";
                requestObjPost.ContentType = "application/json";

                try
                {
                    using (var streamWriter = new StreamWriter(requestObjPost.GetRequestStream()))
                    {
                        streamWriter.Write("");
                        streamWriter.Flush();
                        streamWriter.Close();

                        var httpResponse = (HttpWebResponse)requestObjPost.GetResponse();

                        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        {
                            var result = streamReader.ReadToEnd();

                            //Guardar cookie con el token de inicio de sesion
                            HttpContext.Response.Cookies.Add(new HttpCookie("userID", result));

                            return(RedirectToAction("Index", "Chat"));
                        }
                    }
                }
                catch (Exception)
                {
                    ViewBag.Message = "Usuario o contraseña incorrecto";

                    return(View());
                }
            }
            else
            {
                ViewBag.Message = "Credenciales incorrectas";
                return(View());
            }
        }
Ejemplo n.º 2
0
        public ActionResult CrearUsuario(Usuario user)
        {
            bool repetido = false;

            List <Usuario> users = obtenerPersonas();

            foreach (var item in users)
            {
                if (user.username == item.username)
                {
                    repetido = true;
                    break;
                }
            }

            if (!repetido)
            {
                try
                {
                    //Cifrar Contrase;a

                    int cifradoValue = user.password.Length;

                    SDES   cipher            = new SDES();
                    string contrasenaCifrado = cipher.CifrarTexto(user.password, cifradoValue);

                    user.password = contrasenaCifrado;


                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri("https://localhost:44316/api/users");

                        var postJob = client.PostAsJsonAsync <Usuario>("users", user);
                        postJob.Wait();

                        var postResult = postJob.Result;
                        if (postResult.IsSuccessStatusCode)
                        {
                            return(RedirectToAction("Login", "Login"));
                        }
                        else
                        {
                            return(Content("<script language='javascript' type='text/javascript'>alert('Error');</script>"));
                        }
                    }
                }
                catch (Exception e)
                {
                    return(RedirectToAction("Login", "Login"));
                }
            }
            else
            {
                return(Content("<script language='javascript' type='text/javascript'>alert('Prueba con otro nombre');</script>"));
            }
        }
Ejemplo n.º 3
0
        public ActionResult SubirArchivo(HttpPostedFileBase file, string persona)
        {
            try
            {
                string token        = HttpContext.Request.Cookies["userID"].Value;
                int    cifradoValue = Int16.Parse(HttpContext.Request.Cookies["cifrado"].Value);

                //Subir archivo al servidor
                string path = Path.Combine(Directories.directorioUploads, Path.GetFileName(file.FileName) ?? "");
                UploadFile(path, file);

                //Comprimir
                string rutaComprimido = LZW.comprimirArchivo(path, Directories.directorioTemporal);

                //Cifrar
                SDES   cipher      = new SDES();
                string rutaCifrado = cipher.CifrarArchivo(rutaComprimido, Directories.directorioArchivos, cifradoValue);

                //Pasar ruta como parametro
                string rutaAmigable = rutaCifrado.Replace("/", "~");
                rutaAmigable = rutaAmigable.Replace(@"\", "~");

                string mensaje = $"<a href=\"/Chat/Descargar?path={rutaAmigable}\" onclick=\"clickAndDisable(this);\">{file.FileName}</a>";

                MensajeModelo nuevo = new MensajeModelo();
                nuevo.mensaje   = cipher.CifrarTexto(mensaje, cifradoValue);
                nuevo.receptor  = persona;
                nuevo.receptor  = nuevo.receptor.Replace(" ", "");
                nuevo.esArchivo = true;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:44316/api/chat");
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);

                    var postJob = client.PostAsJsonAsync <MensajeModelo>("chat", nuevo);
                    postJob.Wait();

                    var postResult = postJob.Result;
                    if (postResult.IsSuccessStatusCode)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        return(RedirectToAction("Login", "Login"));
                    }
                }

                return(RedirectToAction("Index", "Chat"));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Login", "Login"));
            }
        }
Ejemplo n.º 4
0
        public ActionResult Index(string persona, string mensaje)
        {
            try
            {
                string token        = HttpContext.Request.Cookies["userID"].Value;
                int    cifradoValue = Int16.Parse(HttpContext.Request.Cookies["cifrado"].Value);

                SDES   cipher         = new SDES();
                string mensajeCifrado = cipher.CifrarTexto(mensaje, cifradoValue);

                MensajeModelo nuevo = new MensajeModelo();
                nuevo.mensaje   = mensajeCifrado;
                nuevo.receptor  = persona;
                nuevo.receptor  = nuevo.receptor.Replace(" ", "");
                nuevo.esArchivo = false;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:44316/api/chat");
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);

                    var postJob = client.PostAsJsonAsync <MensajeModelo>("chat", nuevo);
                    postJob.Wait();

                    var postResult = postJob.Result;
                    if (postResult.IsSuccessStatusCode)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        return(RedirectToAction("Login", "Login"));
                    }
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction("Login", "Login"));
            }
        }
        public FileContentResult TransporteDeDatos([FromForm] int clave)
        {
            try
            {
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivosCompresos\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivosCompresos\\");
                }
                if (!Directory.Exists(_environment.WebRootPath + "\\ArchivosCifrados\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\ArchivosCifrados\\");
                }

                var rutaOriginal1 = Path.GetFullPath(@"ManejoInformacion\" + "producto.csv");
                var rutaOriginal2 = Path.GetFullPath(@"ManejoInformacion\" + "sucursal.csv");
                var rutaOriginal3 = Path.GetFullPath(@"ManejoInformacion\" + "sucursal-producto.csv");
                ////Primer Archivo Producto
                using (var stream = new FileStream(@"C:\Users\HRZCz\OneDrive\Escritorio\URL-Primer Ciclo 2020\Estructura de datos 2\Laboratorio\ProyectoSegundaConvocatoria_EDII\ProyectoSegundaConvocatoria\PROJED2SEGUNDA\PROJED2SEGUNDA\ManejoInformacion\Llaves\Llave.txt", FileMode.OpenOrCreate))
                {
                    using (var reader = new StreamWriter(stream))
                    {
                        reader.Write(clave);
                    }
                }
                SDES modeloSdes1 = new SDES();
                var  OpsDic      = modeloSdes1.LeerOperaciones(@"C:\Users\HRZCz\OneDrive\Escritorio\URL-Primer Ciclo 2020\Estructura de datos 2\Laboratorio\ProyectoSegundaConvocatoria_EDII\ProyectoSegundaConvocatoria\PROJED2SEGUNDA\PROJED2SEGUNDA\ManejoInformacion\Llaves\Oper.txt");
                var  binaryKey   = string.Empty;
                modeloSdes1.VerificarLLave(clave.ToString(), ref binaryKey);
                var key1  = string.Empty;
                var key2  = string.Empty;
                var sbox0 = modeloSdes1.CrearSBox0();
                var sbox1 = modeloSdes1.CrearSBox1();
                modeloSdes1.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesCifrados = modeloSdes1.CifrarTexto(rutaOriginal1, OpsDic, key1, key2, sbox0, sbox1);
                key1 = string.Empty;
                key2 = string.Empty;
                modeloSdes1.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesDecifrados = modeloSdes1.DescifrarTexto(bytesCifrados, OpsDic, key1, key2, sbox0, sbox1);
                var vec1            = rutaOriginal1.Split(@"\");
                var vec2            = vec1[vec1.Length - 1].Split(".");
                var pathHuffman     = _environment.WebRootPath + "\\ArchivosCifrados\\";
                using (var stream = new FileStream(pathHuffman + vec1[vec1.Length - 1], FileMode.OpenOrCreate))
                {
                    using (var reader = new BinaryWriter(stream))
                    {
                        foreach (var item in bytesDecifrados)
                        {
                            reader.Write(item);
                        }
                    }
                }
                var pathHuffman2 = _environment.WebRootPath + "\\ArchivosCompresos\\";
                Huffman.Instancia.CompresiónHuffman(pathHuffman + vec1[vec1.Length - 1], vec2, pathHuffman2);


                ////Segundo Archivo Sucursal
                SDES modeloSdes2 = new SDES();
                key1 = string.Empty;
                key2 = string.Empty;
                modeloSdes2.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesCifrados_2 = modeloSdes2.CifrarTexto(rutaOriginal2, OpsDic, key1, key2, sbox0, sbox1);
                key1 = string.Empty;
                key2 = string.Empty;
                modeloSdes2.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesDecifrados2 = modeloSdes2.DescifrarTexto(bytesCifrados_2, OpsDic, key1, key2, sbox0, sbox1);
                var vec1_2           = rutaOriginal2.Split(@"\");
                var vec2_2           = vec1_2[vec1_2.Length - 1].Split(".");
                var pathHuffman_2    = _environment.WebRootPath + "\\ArchivosCifrados\\";
                using (var stream = new FileStream(pathHuffman_2 + vec1_2[vec1_2.Length - 1], FileMode.OpenOrCreate))
                {
                    using (var reader = new BinaryWriter(stream))
                    {
                        foreach (var item in bytesDecifrados2)
                        {
                            reader.Write(item);
                        }
                    }
                }
                var pathHuffman2_2 = _environment.WebRootPath + "\\ArchivosCompresos\\";
                Huffman.Instancia.CompresiónHuffman(pathHuffman_2 + vec1_2[vec1_2.Length - 1], vec2_2, pathHuffman2_2);


                ////Tercer Archivo Sucursal-Producto
                SDES modeloSdes3 = new SDES();
                key1 = string.Empty;
                key2 = string.Empty;
                modeloSdes3.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesCifrados_3 = modeloSdes3.CifrarTexto(rutaOriginal3, OpsDic, key1, key2, sbox0, sbox1);
                key1 = string.Empty;
                key2 = string.Empty;
                modeloSdes3.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
                var bytesDecifrados3 = modeloSdes3.DescifrarTexto(bytesCifrados_3, OpsDic, key1, key2, sbox0, sbox1);
                var vec1_3           = rutaOriginal3.Split(@"\");
                var vec2_3           = vec1_3[vec1_3.Length - 1].Split(".");
                var pathHuffman_3    = _environment.WebRootPath + "\\ArchivosCifrados\\";
                using (var stream = new FileStream(pathHuffman_3 + vec1_3[vec1_3.Length - 1], FileMode.OpenOrCreate))
                {
                    using (var reader = new BinaryWriter(stream))
                    {
                        foreach (var item in bytesDecifrados3)
                        {
                            reader.Write(item);
                        }
                    }
                }
                var pathHuffman2_3 = _environment.WebRootPath + "\\ArchivosCompresos\\";
                Huffman.Instancia.CompresiónHuffman(pathHuffman_3 + vec1_3[vec1_3.Length - 1], vec2_3, pathHuffman2_3);


                ////Manejo de archivo ZIP. resultante con las compresiones de los metodos
                string ruta1   = pathHuffman2 + "producto.huff";
                string ruta2   = pathHuffman2_2 + "sucursal.huff";
                string ruta3   = pathHuffman2_3 + "sucursal-producto.huff";
                string cadena1 = string.Empty;
                string cadena2 = string.Empty;
                string cadena3 = string.Empty;
                using (StreamReader sr = new StreamReader(ruta1))
                {
                    cadena1 = sr.ReadToEnd();
                }
                using (StreamReader sr = new StreamReader(ruta2))
                {
                    cadena2 = sr.ReadToEnd();
                }
                using (StreamReader sr = new StreamReader(ruta3))
                {
                    cadena3 = sr.ReadToEnd();
                }
                byte[] file1 = Encoding.ASCII.GetBytes(cadena1);
                byte[] file2 = Encoding.ASCII.GetBytes(cadena2);
                byte[] file3 = Encoding.ASCII.GetBytes(cadena3);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (var Archivo = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        var Zip1 = Archivo.CreateEntry("producto.huff", CompressionLevel.Fastest);
                        using (var zipStream1 = Zip1.Open()) zipStream1.Write(file1, 0, file1.Length);
                        var Zip2 = Archivo.CreateEntry("sucursal.huff", CompressionLevel.Fastest);
                        using (var zipStream2 = Zip2.Open()) zipStream2.Write(file2, 0, file2.Length);
                        var Zip3 = Archivo.CreateEntry("sucursal-producto.huff", CompressionLevel.Fastest);
                        using (var zipStream3 = Zip3.Open()) zipStream3.Write(file3, 0, file3.Length);
                    }

                    return(File(ms.ToArray(), "Application/zip", "ArchivoFinal.zip"));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Clave vacia o erronea", ex);
            }
        }
Ejemplo n.º 6
0
        public void PostProductos([FromBody] object value)
        {
            var  val           = Newtonsoft.Json.JsonConvert.SerializeObject(value);
            Data datos         = Newtonsoft.Json.JsonConvert.DeserializeObject <Data>(val);
            var  rutaOriginal1 = Path.GetFullPath(@"obj\" + datos.NombreArchivo1);
            var  rutaOriginal2 = Path.GetFullPath(@"obj\" + datos.NombreArchivo2);
            var  rutaOriginal3 = Path.GetFullPath(@"obj\" + datos.NombreArchivo3);

            using (var stream = new FileStream(@"D:\Escritorio\ProyectEDii\ProyectoED2\Keys\Llave.txt", FileMode.OpenOrCreate))
            {
                using (var reader = new StreamWriter(stream))
                {
                    reader.Write(datos.clave);
                }
            }
            SDES modeloSdes1 = new SDES();
            var  OpsDic      = modeloSdes1.LeerOperaciones(@"D:\Escritorio\ProyectEDii\ProyectoED2\Keys\Oper.txt");
            var  binaryKey   = string.Empty;

            modeloSdes1.VerificarLLave(datos.clave, ref binaryKey);
            var key1  = string.Empty;
            var key2  = string.Empty;
            var sbox0 = modeloSdes1.CrearSBox0();
            var sbox1 = modeloSdes1.CrearSBox1();

            modeloSdes1.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesCifrados = modeloSdes1.CifrarTexto(rutaOriginal1, OpsDic, key1, key2, sbox0, sbox1);

            key1 = string.Empty;
            key2 = string.Empty;
            modeloSdes1.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesDecifrados = modeloSdes1.DescifrarTexto(bytesCifrados, OpsDic, key1, key2, sbox0, sbox1);
            var vec1            = rutaOriginal1.Split(@"\");
            var vec2            = vec1[vec1.Length - 1].Split(".");
            var pathHuffman     = Path.GetFullPath("Archivos Cifrados//");

            using (var stream = new FileStream(pathHuffman + vec1[vec1.Length - 1], FileMode.OpenOrCreate))
            {
                using (var reader = new BinaryWriter(stream))
                {
                    foreach (var item in bytesDecifrados)
                    {
                        reader.Write(item);
                    }
                }
            }
            var pathHuffman2 = Path.GetFullPath("Archivos Comprimidos//");

            Huffman.Huffman.Instancia.CompresiónHuffman(pathHuffman + vec1[vec1.Length - 1], vec2, pathHuffman2);
            //arch2
            SDES modeloSdes2 = new SDES();

            key1 = string.Empty;
            key2 = string.Empty;
            modeloSdes2.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesCifrados2 = modeloSdes2.CifrarTexto(rutaOriginal2, OpsDic, key1, key2, sbox0, sbox1);

            key1 = string.Empty;
            key2 = string.Empty;
            modeloSdes2.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesDecifrados2 = modeloSdes2.DescifrarTexto(bytesCifrados2, OpsDic, key1, key2, sbox0, sbox1);
            var vec12            = rutaOriginal2.Split(@"\");
            var vec22            = vec12[vec12.Length - 1].Split(".");
            var pathHuffman20    = Path.GetFullPath("Archivos Cifrados//");

            using (var stream = new FileStream(pathHuffman20 + vec12[vec12.Length - 1], FileMode.OpenOrCreate))
            {
                using (var reader = new BinaryWriter(stream))
                {
                    foreach (var item in bytesDecifrados2)
                    {
                        reader.Write(item);
                    }
                }
            }
            var pathHuffman22 = Path.GetFullPath("Archivos Comprimidos//");

            Huffman.Huffman.Instancia.CompresiónHuffman(pathHuffman20 + vec12[vec12.Length - 1], vec22, pathHuffman22);
            //arch3
            SDES modeloSdes3 = new SDES();

            key1 = string.Empty;
            key2 = string.Empty;
            modeloSdes3.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesCifrados23 = modeloSdes3.CifrarTexto(rutaOriginal3, OpsDic, key1, key2, sbox0, sbox1);

            key1 = string.Empty;
            key2 = string.Empty;
            modeloSdes3.GenerarLlaves(OpsDic, binaryKey, ref key1, ref key2);
            var bytesDecifrados23 = modeloSdes3.DescifrarTexto(bytesCifrados23, OpsDic, key1, key2, sbox0, sbox1);
            var vec13             = rutaOriginal3.Split(@"\");
            var vec23             = vec13[vec13.Length - 1].Split(".");
            var pathHuffman3      = Path.GetFullPath("Archivos Cifrados//");

            using (var stream = new FileStream(pathHuffman3 + vec13[vec13.Length - 1], FileMode.OpenOrCreate))
            {
                using (var reader = new BinaryWriter(stream))
                {
                    foreach (var item in bytesDecifrados23)
                    {
                        reader.Write(item);
                    }
                }
            }
            var pathHuffman23 = Path.GetFullPath("Archivos Comprimidos//");

            Huffman.Huffman.Instancia.CompresiónHuffman(pathHuffman3 + vec13[vec13.Length - 1], vec23, pathHuffman23);
        }