Exemplo n.º 1
0
        //Función que devuelve la información de los archivos según la etiqueta indicada
        private static XDocument LeerInfo(string etiqueta)
        {
            XDocument xdoc_interno = null, xdoc_leido = null; string cadena_xdoc = "";

            try
            {
                xdoc_interno = XDocument.Load(rutaArchivo);
                foreach (XElement xEle in xdoc_interno.Root.Elements("info"))
                {
                    if (xEle.Attribute("etiqueta").Value.ToString() == etiqueta)
                    {
                        cadena_xdoc = xEle.Attribute("bytes").Value.ToString();
                    }
                }
                xdoc_interno = null;
                cadena_xdoc  = Cifrado.Cripto(cadena_xdoc);
                //cadena_xdoc = Cifrado.Descifrar(cadena_xdoc);

                if (cadena_xdoc != null)
                {
                    xdoc_leido = XDocument.Parse(cadena_xdoc);
                }
            }
            catch (Exception ex)
            {
                xdoc_leido = null;
            }
            return(xdoc_leido);
        }
Exemplo n.º 2
0
        protected void lgnLogin_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
        {
            try
            {
                Login   loLogin      = (Login)sender;
                TextBox txtBaseDatos = (TextBox)loLogin.FindControl("DataBase");

                Administrador loAdministrador = new Administrador();
                Cifrado       loCifrado       = new Cifrado(Criptografia.Comun.Definiciones.TipoCifrado.AES);
                loConexion = new Conexion()
                {
                    BaseDatos    = txtBaseDatos.Text,
                    Credenciales = new Credenciales()
                    {
                        Cifrado     = loCifrado,
                        Contrasenia = loCifrado.Cifrar(loLogin.Password),
                        Usuario     = loLogin.UserName
                    },
                    IdAplicacion = ConfigurationManager.AppSettings["ID"],
                    Tipo         = Definiciones.TipoConexion.CredencialesExplicitas,
                    TipoCliente  = Definiciones.TipoCliente.Oracle
                };
                Sesion loSesion = loAdministrador.ObtenerSesion(loConexion);


                e.Authenticated   = loSesion.Estatus == Seguridad.Comun.Definiciones.EstatusSesion.Iniciada;
                Session["Sesion"] = loSesion;
            }
            catch (Exception)
            {
                e.Authenticated = false;
            }
        }
Exemplo n.º 3
0
        //Procedimiento que actualiza los datos en los archivos
        private static void ActualizarInfo(XDocument xdoc_guardar, string etiqueta)
        {
            XDocument xdoc_interno = null;

            try
            {
                string cadena_xdoc = xdoc_guardar.ToString();
                cadena_xdoc = Cifrado.Cripto(cadena_xdoc, "E");
                //cadena_xdoc = Cifrado.Cifrar(cadena_xdoc);

                xdoc_interno = XDocument.Load(rutaArchivo);
                foreach (XElement xEle in xdoc_interno.Root.Elements("info"))
                {
                    if (xEle.Attribute("etiqueta").Value.ToString() == etiqueta)
                    {
                        xEle.SetAttributeValue("bytes", cadena_xdoc);
                    }
                }
                xdoc_interno.Save(rutaArchivo);
            }
            catch (Exception ex)
            {
                xdoc_interno = null;
            }
        }
Exemplo n.º 4
0
        internal void SesionDB()
        {
            #region Sesion usuario base de datos
            try
            {
                Administrador loAdministrador = new Administrador();
                Cifrado       loCifrado       = new Cifrado(Definiciones.TipoCifrado.AES);
                Conexion      loConexion      = new Conexion()
                {
                    BaseDatos    = "siil",
                    Credenciales = new Credenciales()
                    {
                        Cifrado     = loCifrado,
                        Contrasenia = loCifrado.Cifrar(ConfigurationManager.AppSettings["Clave"]),
                        Usuario     = ConfigurationManager.AppSettings["Usuario"]
                    },
                    Tipo        = Dapesa.Comun.Definiciones.TipoConexion.CredencialesExplicitas,
                    TipoCliente = Dapesa.Comun.Definiciones.TipoCliente.Oracle
                };
                Sesion loSesion = loAdministrador.ObtenerSesion(loConexion);

                Session["SesionDB"] = loSesion;
            }
            catch (Exception)
            {
            }
            #endregion
        }
Exemplo n.º 5
0
        public async Task <IActionResult> generar(int p, int q)
        {
            string       rutaPublic  = $"./keys/public.key";
            string       rutaPrivate = $"./keys/private.key";
            string       rutaZip     = $"./keys/keys.zip";
            FileStream   publicKey   = new FileStream(rutaPublic, FileMode.OpenOrCreate, FileAccess.Write);
            FileStream   privateKey  = new FileStream(rutaPrivate, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter pblc        = new StreamWriter(publicKey);
            StreamWriter prvt        = new StreamWriter(privateKey);

            try
            {
                Cifrado       llaves = new Cifrado();
                List <string> keys   = llaves.generarClaves(p, q);
                pblc.Write(keys[0]);
                pblc.Close();
                prvt.Write(keys[1]);
                prvt.Close();

                using (var file = ZipFile.Open(rutaZip, ZipArchiveMode.Create))
                {
                    file.CreateEntryFromFile(rutaPublic, Path.GetFileName(rutaPublic));
                    file.CreateEntryFromFile(rutaPrivate, Path.GetFileName(rutaPrivate));
                }

                System.IO.File.Delete(rutaPublic);
                System.IO.File.Delete(rutaPrivate);

                return(StatusCode(200));
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> cifrarDescifrar([FromForm] IFormFile file, [FromForm] IFormFile key, string nombre)
        {
            Cifrado cifDes = new Cifrado();
            string  path   = @".\temporales\";

            string[] separado    = (key.FileName).Split('.');
            string   terminacion = separado[0];

            try
            {
                using (var filestream = new FileStream((path + file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(filestream);

                    filestream.Close();
                }

                using (var filestream2 = new FileStream((path + key.FileName), FileMode.Create))
                {
                    await key.CopyToAsync(filestream2);

                    filestream2.Close();
                }

                string     pathFile = path + file.FileName;
                FileStream fileS    = new FileStream(pathFile, FileMode.Open, FileAccess.Read);
                string     linea    = System.IO.File.ReadAllText(path + key.FileName, System.Text.Encoding.Default);

                if (terminacion == "public")
                {
                    FileStream  nuevo = new FileStream(@".\" + nombre + ".txt", FileMode.Create, FileAccess.ReadWrite);
                    string[]    data  = linea.Split(',');
                    int         n     = Convert.ToInt32(data[0]);
                    int         e     = Convert.ToInt32(data[1]);
                    List <byte> bytes = cifDes.cifrar(fileS, n, e);
                    nuevo.Write(bytes.ToArray());
                    nuevo.Close();
                    System.IO.File.Delete(path + file.FileName);
                    System.IO.File.Delete(path + key.FileName);
                }
                else if (terminacion == "private")
                {
                    FileStream  nuevo = new FileStream(@".\" + nombre + ".txt", FileMode.Create, FileAccess.ReadWrite);
                    string[]    data  = linea.Split(',');
                    int         n     = Convert.ToInt32(data[0]);
                    int         d     = Convert.ToInt32(data[1]);
                    List <byte> bytes = cifDes.descifrar(fileS, n, d);
                    nuevo.Write(bytes.ToArray());
                    nuevo.Close();
                    System.IO.File.Delete(path + file.FileName);
                    System.IO.File.Delete(path + key.FileName);
                }
                return(StatusCode(200));
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 7
0
        //Realiza la conexión con la BBDD, en caso de fallar muestra un mensaje de error por pantalla
        //Si se realiza correctamente la inserción se cambia a la ventana principal junto con la de configuración
        private void connBBDD()
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Formularios\MiBaseDeDatos.mdf;Integrated Security=True"))
            {
                using (SqlCommand cmd = new SqlCommand("Select * From Usuario where id =  '" + textBox_usuario.Text.ToLower() + "'", conn))
                {
                    conn.Open();
                    using (SqlDataReader rd = cmd.ExecuteReader())
                    {
                        if (rd.HasRows)
                        {
                            MessageBox.Show("Error: El usuario ya existe", "Error", MessageBoxButtons.OK);
                            rd.Close();
                        }
                        else
                        {
                            rd.Close();

                            //Inicializamos el DataSet que conecta con la tabla usuarios
                            BBDDDataSetTableAdapters.UsuarioTableAdapter usuarioTableAdapter;
                            usuarioTableAdapter = new BBDDDataSetTableAdapters.UsuarioTableAdapter();
                            String usuario    = textBox_usuario.Text.ToLower();
                            String contraseña = textBox_contraseña.Text;
                            String sal        = Cifrado.CrearClaveAleatoria(32);
                            String hash       = Cifrado.obtenerHashCifrado(contraseña, sal);

                            //Insertamos el nuevo usuario en la base de datos
                            usuarioTableAdapter.Insert(usuario, hash, null, null, null, null, false, false, false, sal);

                            this.Hide();
                            Formularios.Principal     form  = new Formularios.Principal();
                            Formularios.Configuracion form2 = new Formularios.Configuracion();

                            form.StartPosition  = FormStartPosition.CenterScreen;
                            form2.StartPosition = FormStartPosition.CenterScreen;

                            //Cargamos el usuario en el resto de formularios
                            form._usuario    = usuario;
                            form2._usuario   = usuario;
                            form._password   = hash;
                            form2._principal = form;
                            try
                            {
                                form2.ShowDialog();
                                form.ShowDialog();
                            }
                            catch (System.NullReferenceException)
                            {
                            }
                            this.Close();
                        }
                    }

                    conn.Close();
                }
            }
        }
Exemplo n.º 8
0
        //Desencripta los archivos seleccionados del panel de control derecho en la carpeta de descarga seleccionada
        private void btn_decrypt_Click(object sender, EventArgs e)
        {
            //GongSolutions.Shell.ShellItem[] elementos = Vista_carpeta.SelectedItems;
            //foreach(GongSolutions.Shell.ShellItem elemento in elementos)
            //{
            //String rutaElemento = elemento.FileSystemPath;
            foreach (String rutaElemento in rutas)
            {
                String nombreElemento = System.IO.Path.GetFileName(rutaElemento);
                String PassBD         = buscarArchivoBD(nombreElemento);
                String nombre         = System.IO.Path.GetFileNameWithoutExtension(rutaElemento);
                String ruta           = System.IO.Path.GetDirectoryName(rutaElemento);
                String ficheroDestino = System.IO.Path.Combine(_dir_descarga, nombre);
                String error          = "";
                if (PassBD == "")
                {
                    error += "El archivo " + nombreElemento + " no está cifrado\n";
                }
                else
                {
                    Byte[] PassMaestra   = Cifrado.GenerarClaveByte(_password, 32);
                    String PassArchivo   = Cifrado.DescifrarPassArchivoAES(PassBD, PassMaestra);
                    Byte[] ContAleatoria = Cifrado.GenerarClaveByte(PassArchivo, 16);
                    //Comprueba si la extensión del archivo es AES o RC4
                    switch (System.IO.Path.GetExtension(rutaElemento))
                    {
                    case ".aes":     //Caso de que sea aes
                        //Desciframos el archivo e AES
                        Cifrado.DescifrarAES(rutaElemento, ficheroDestino, ContAleatoria);
                        break;

                    case ".rc4":     //Caso de que sea RC4
                        //Desciframos el archivo en RC4
                        Cifrado.RC4(rutaElemento, ficheroDestino, PassArchivo);

                        break;

                    default:
                        return;
                    }
                }

                if (error != "")
                {
                    MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Todos los archivos se han descifrado con éxito", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            listaArchivos.Clear();
            rutas.Clear();
            Process.Start("explorer.exe", _dir_descarga);
        }
Exemplo n.º 9
0
        private void ValidarCredenciales()
        {
            if (!this.CamposRequeridos())
            {
                return;
            }

            try
            {
                #region Autenticación

                Administrador loAdministrador = new Administrador();
                Cifrado       loCifrado       = new Cifrado(Definiciones.TipoCifrado.AES);

                this._oSesion = loAdministrador.ObtenerSesion(new Conexion()
                {
                    Credenciales = new Credenciales()
                    {
                        Cifrado     = loCifrado,
                        Contrasenia = loCifrado.Cifrar(txtContrasenia.Text),
                        Usuario     = txtUsuario.Text
                    },
                    IdAplicacion = ConfigurationManager.AppSettings["ID"],
                    IdServicio   = txtBaseDatos.Text,
                    Puerto       = ConfigurationManager.AppSettings["BDPuerto"],
                    Servidor     = ConfigurationManager.AppSettings["BDServidor"],
                    Tipo         = Dapesa.Comun.Definiciones.TipoConexion.NoTNSNAMES,
                    TipoCliente  = Dapesa.Comun.Definiciones.TipoCliente.Oracle
                });

                if (_oSesion.Estatus != Dapesa.Seguridad.Comun.Definiciones.EstatusSesion.Iniciada)
                {
                    return;
                }

                lblMensaje.Text = string.Empty;
                this.Hide();



                #endregion
            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show(ex.Message + "\r\nFuente: " + ex.Source, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                ex.Source       = string.Empty;
                lblMensaje.Text = "Credenciales no válidas. Intenta nuevamente por favor." + ex.Source;
#endif
                txtContrasenia.Text = string.Empty;
                txtUsuario.SelectAll();
                txtUsuario.Focus();
            }
        }
Exemplo n.º 10
0
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         this.txtResult.Text  = string.Empty;
         this.txtResult.Text += "\nTexto Decifrado " + Cifrado.DescifradoTexto(this.textData.Text);
     }
     catch (Exception ex)
     {
         this.txtResult.Text = "Error :" + ex.Message;
     }
 }
Exemplo n.º 11
0
        protected void lgnLogin_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
        {
            #region IniciarSesion con directorio activo
            try
            {
                Login   loLogin    = (Login)sender;
                TextBox txtDominio = (TextBox)loLogin.FindControl("Domain");

                PrincipalContext loLDAP = new PrincipalContext(ContextType.Domain, txtDominio.Text, loLogin.UserName, loLogin.Password);
                Dapesa.Comun.DirectorioActivo.Reglas.Usuario loUsuario = new Dapesa.Comun.DirectorioActivo.Reglas.Usuario();
                Cifrado loCifrado = new Cifrado(Dapesa.Criptografia.Comun.Definiciones.TipoCifrado.AES);

                Sesion loSesion = new Sesion()
                {
                    Conexion = new Conexion()
                    {
                        Nombre       = loLDAP.Name,
                        Servidor     = loLDAP.ConnectedServer,
                        Credenciales = new Credenciales()
                        {
                            Cifrado     = loCifrado,
                            Contrasenia = loCifrado.Cifrar(loLogin.Password),
                            Usuario     = loLogin.UserName
                        },
                    },
                    Estatus = (loLDAP.ValidateCredentials(loLogin.UserName, loLogin.Password)) ? Dapesa.Seguridad.Comun.Definiciones.EstatusSesion.Iniciada : Dapesa.Seguridad.Comun.Definiciones.EstatusSesion.NoIniciada,
                    Usuario = new Usuario()
                    {
                        Estatus  = Dapesa.Seguridad.Comun.Definiciones.EstatusUsuario.Valido,
                        Sucursal = new List <Sucursal>()
                        {
                            new Sucursal()
                        }
                    },
                };

                e.Authenticated = loSesion.Estatus == Dapesa.Seguridad.Comun.Definiciones.EstatusSesion.Iniciada && loUsuario.PerteneceA(loSesion, ConfigurationManager.AppSettings["GrupoValidez"]);

                if (e.Authenticated)
                {
                    loSesion.Usuario.Nombre = loUsuario.ObtenerPropiedad(loSesion, "name");
                    loSesion.Usuario.Sucursal[0].Descripcion = loUsuario.ObtenerPropiedad(loSesion, "l");
                    SesionDB();
                }

                Session["Sesion"] = loSesion;
            }
            catch (Exception)
            {
                e.Authenticated = false;
            }
            #endregion
        }
        private bool ComprobarUsuario(String nombreUsuario, String password)
        {
            var miDic = new Dictionary <String, String>()
            {
                { "username", nombreUsuario }, { "password", Cifrado.GetSHA1(password) }
            };

            Session["usuarioLogin"] = nombreUsuario;
            Session["passLogin"]    = Cifrado.GetSHA1(password);

            var usuarioTemp = _Usuarios.Get(miDic, (String)Session["usuarioLogin"], (String)Session["passLogin"]);

            return(usuarioTemp.Any());
        }
Exemplo n.º 13
0
        public void Operar()
        {
            switch (Extension)
            {
            case "txt":
                CifradoEspiral = new Cifrado(Clave, DireccionRecorrido, NombreArchivo, RutaAbsolutaArchivo, RutaAbsolutaServer);
                CifradoEspiral.Cifrar();
                break;

            case "cif":
                DescifradoEspiral = new Descifrado(Clave, DireccionRecorrido, NombreArchivo, RutaAbsolutaArchivo, RutaAbsolutaServer);
                DescifradoEspiral.Descifrar();
                break;
            }
        }
Exemplo n.º 14
0
 public ActionResult ModificarUsuario(usuarios_axsis usuarios)
 {
     if (ModelState.IsValid)
     {
         using (BD_CRUD_AxsisEntities db = new BD_CRUD_AxsisEntities())
         {
             //si quito esta linea de codigo el estatusPermiso me lo pone como null y no se muestra en el index
             usuarios.contrasena         = Cifrado.ComputeHash(usuarios.contrasena, "SHA512", GetBytes("MyDemo"));
             usuarios.contrasena_confirm = Cifrado.ComputeHash(usuarios.contrasena_confirm, "SHA512", GetBytes("MyDemo"));
             db.Entry(usuarios).State    = EntityState.Modified;
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
     }
     return(View(usuarios));
 }
Exemplo n.º 15
0
        protected override void OnStart(string[] args)
        {
            try
            {
                this._oLog.WriteEntry("Configurando elementos de diagnóstico...", EventLogEntryType.Information);

                #region Configuración elementos diagnóstico

                Cifrado loCifrado = new Cifrado(Definiciones.TipoCifrado.AES);

                this._oDiagnostico = new Reglas.Diagnostico(new Entidades.Diagnostico()
                {
                    DirectorioDiagnostico = ConfigurationManager.AppSettings["DirectorioDiagnostico"],
                    DirectorioEntrada     = ConfigurationManager.AppSettings["DirectorioEntrada"],
                    DirectorioProcesados  = ConfigurationManager.AppSettings["DirectorioProcesados"],
                    HoraDetencion         = ConfigurationManager.AppSettings["HoraDetencion"],
                    HoraDetencionSabado   = ConfigurationManager.AppSettings["HoraDetencionSabado"],
                    HoraReanudacion       = ConfigurationManager.AppSettings["HoraReanudacion"],
                    Mensaje = new Correo()
                    {
                        Asunto       = ConfigurationManager.AppSettings["CorreoAsunto"],
                        CC           = (string.IsNullOrEmpty(ConfigurationManager.AppSettings["CorreoCC"])) ? null : ConfigurationManager.AppSettings["CorreoCC"],
                        Credenciales = new Credenciales {
                            Cifrado     = loCifrado,
                            Contrasenia = loCifrado.Cifrar(ConfigurationManager.AppSettings["CorreoCP"]),
                            Usuario     = ConfigurationManager.AppSettings["CorreoCuenta"]
                        },
                        Destinatario = ConfigurationManager.AppSettings["CorreoDestinatario"],
                        Puerto       = int.Parse(ConfigurationManager.AppSettings["CorreoPuerto"]),
                        Remitente    = ConfigurationManager.AppSettings["CorreoCuenta"],
                        Servidor     = ConfigurationManager.AppSettings["CorreoServidor"]
                    }
                });

                #endregion

                this._oLog.WriteEntry("Proceso iniciado...", EventLogEntryType.Information);
                tmrProceso.Interval = int.Parse(ConfigurationManager.AppSettings["TemporizadorProceso"]);
                tmrCorreo.Interval  = int.Parse(ConfigurationManager.AppSettings["TemporizadorCorreo"]);
                tmrProceso.Enabled  = true;
                tmrCorreo.Enabled   = true;
            }
            catch (Exception ex)
            {
                this._oLog.WriteEntry("Error: " + ex.Message + ". Fuente: " + ex.Source, EventLogEntryType.Error);
            }
        }
Exemplo n.º 16
0
        //Reset, para cuando se le da home y que vuelva instanciar
        public void Reset()
        {
            switch (Extension)
            {
            case "cif":
                File.Delete(RutaAbsolutaServer + NombreArchivo + ".txt");
                DescifradoEspiral = new Descifrado(0, "", "", "", "");
                break;

            case "txt":
                File.Delete(RutaAbsolutaServer + NombreArchivo + ".cif");
                CifradoEspiral = new Cifrado(0, "", "", "", "");
                break;
            }
            Data.Instancia.ArchivoCargado    = false;
            Data.Instancia.EleccionOperacion = false;
        }
Exemplo n.º 17
0
        public string[] SavePass(string path, string nameWithExtention, string text)
        {
            Cifrado x = new Cifrado();

            string[] vsLogin = { };
            string   cadena;

            x.IniciarAES("LlaveSimetrica");
            string file2 = CreateFile(path, nameWithExtention, x.Cifrar(text));

            if (File.Exists(file2))
            {
                cadena = x.Decifrar(File.ReadAllText(file2));

                vsLogin = cadena.Split(',');
            }

            return(vsLogin);
        }
Exemplo n.º 18
0
        private void buttonIngresar_Click(object sender, EventArgs e)
        {
            SQLParametros parametros = new SQLParametros();

            parametros.add("@usu", textBoxUsuario.Text);
            //Encripto la contraseña
            parametros.add("@password", Cifrado.Cifrar(textBoxContrasena.Text));

            DataTable DTUsuario;

            if (ConexionDB.Procedure("loginProc", parametros.get(), out DTUsuario))
            {
                Sesion.user_id = Convert.ToDecimal(DTUsuario.Rows[0][0]);
                Sesion.usuario = textBoxUsuario.Text;

                new SeleccionarSucursal().Show(this);
                this.Hide();
            }
        }
Exemplo n.º 19
0
        //Procedimiento que guarda los datos en los archivos por primera vez
        private static void GuardarInfo(XDocument xdoc_guardar, string etiqueta)
        {
            XDocument xdoc_interno = null;

            try
            {
                string cadena_xdoc = xdoc_guardar.ToString();
                cadena_xdoc = Cifrado.Cripto(cadena_xdoc, "E");
                //cadena_xdoc = Cifrado.Cifrar(cadena_xdoc);

                if (etiqueta != "datos")
                {
                    xdoc_interno = XDocument.Load(rutaArchivo);
                }
                else
                {
                    xdoc_interno = new XDocument();
                }
                XElement   xRoot = new XElement("informacion");
                XElement   xInfo = new XElement("info");
                XAttribute xEle  = new XAttribute("etiqueta", etiqueta);
                XAttribute xElb  = new XAttribute("bytes", cadena_xdoc);
                xInfo.Add(xEle);
                xInfo.Add(xElb);
                if (etiqueta != "datos")
                {
                    xdoc_interno.Root.Add(xInfo);
                }
                else
                {
                    xRoot.Add(xInfo);
                    xdoc_interno.Add(xRoot);
                }
                xdoc_interno.Save(rutaArchivo);
                xdoc_interno = null;
            }
            catch (Exception ex)
            {
                xdoc_interno = null;
            }
        }
Exemplo n.º 20
0
        private string PagarServicioJWT(RequestPagarServicios requestPagarServicios, string metodoApiGestoPago)
        {
            String result = string.Empty;
            _ResponsePagarServicios responsePagarServicios = new _ResponsePagarServicios();

            responsePagarServicios.request = ConexionAPI.ObtenerConexion() + requestPagarServicios.ObtenerParametros();

            string dataPost = JsonConvert.SerializeObject(requestPagarServicios);

            String cadenaNormal = Cifrado.CifradoTexto(dataPost);
            String cadenaEscape = Uri.EscapeDataString(Cifrado.CifradoTexto(dataPost));

            byte[] data = UTF8Encoding.UTF8.GetBytes("signed=" + cadenaEscape);
            new Logg().Info("strKey : " + ConexionAPI.secretKey + " | IV: " + ConexionAPI.IV);
            new Logg().Info("signed cadenaEscape =" + cadenaEscape);
            new Logg().Info("signed cadenaNormal =" + cadenaNormal);
            new Logg().Info("Descrypt: " + Cifrado.DescifradoTexto(cadenaNormal));
            string token = new Authenticate().GeneraToken();



            HttpWebRequest request = initRequest(data, metodoApiGestoPago);

            request.Headers.Add("Authorization", "Bearer " + token);
            Stream postStream = request.GetRequestStream();

            postStream.Write(data, 0, data.Length);

            HttpWebResponse response       = request.GetResponse() as HttpWebResponse;
            StreamReader    readerResponse = new StreamReader(response.GetResponseStream());

            result = readerResponse.ReadToEnd();
            Debug.WriteLine("Result ws: " + result);
            Debug.WriteLine("Json Params: " + JsonConvert.SerializeObject(requestPagarServicios));
            Debug.WriteLine("Data Cifrada: " + cadenaNormal);
            Debug.WriteLine("Data Cifrada Escape: " + cadenaEscape);
            Debug.WriteLine("token: " + token);
            return(result);
        }
Exemplo n.º 21
0
        private Sesion EstablecerSesion()
        {
            Administrador loAdministrador = new Administrador();
            Cifrado       loCifrado       = new Cifrado(Criptografia.Comun.Definiciones.TipoCifrado.AES);
            Conexion      loConexion      = new Conexion()
            {
                BaseDatos    = "SIIL",
                Credenciales = new Credenciales()
                {
                    Cifrado     = loCifrado,
                    Contrasenia = loCifrado.Cifrar("isilav"),
                    Usuario     = "SIIL_OWNER"
                },
                Tipo        = Dapesa.Comun.Definiciones.TipoConexion.CredencialesExplicitas,
                TipoCliente = Dapesa.Comun.Definiciones.TipoCliente.Oracle
            };

            Sesion loSesion = loAdministrador.ObtenerSesion(loConexion);

            loSesion.Estatus = Seguridad.Comun.Definiciones.EstatusSesion.Iniciada;
            return(loSesion);
        }
Exemplo n.º 22
0
        private Sesion EstablecerSesion(EventLog poLog)
        {
            Administrador loAdministrador = new Administrador();
            Cifrado       loCifrado       = new Cifrado(Criptografia.Comun.Definiciones.TipoCifrado.AES);
            Conexion      loConexion      = new Conexion()
            {
                BaseDatos    = "SIIL",
                Credenciales = new Credenciales()
                {
                    Cifrado     = loCifrado,
                    Contrasenia = loCifrado.Cifrar(Descifrar(ConfigurationManager.AppSettings["Password"], poLog)),
                    Usuario     = ConfigurationManager.AppSettings["Usuario"]
                },
                Tipo        = Dapesa.Comun.Definiciones.TipoConexion.CredencialesExplicitas,
                TipoCliente = Dapesa.Comun.Definiciones.TipoCliente.Oracle
            };

            Sesion loSesion = loAdministrador.ObtenerSesion(loConexion);

            loSesion.Estatus = Seguridad.Comun.Definiciones.EstatusSesion.Iniciada;
            return(loSesion);
        }
Exemplo n.º 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.txtResult.Text = string.Empty;
                RequestPagarServicios requestPagarServicios = new RequestPagarServicios()
                {
                    IdProducto = 582, IdServicio = 133, Telefono = "4433740472", NumeroReferencia = "718931201466", Monto = 1243
                };
                //this.textData.Text = string.IsNullOrEmpty(this.textData.Text)

                this.textData.Text = JsonConvert.SerializeObject(requestPagarServicios);
                //this.txtResult.Text= Utilerias.CMVCifrarAES256(this.textData.Text);
                string texto = Cifrado.CifradoTexto(this.textData.Text);
                this.txtResult.Text = "Texto Cifrado " + texto;

                this.txtResult.Text += "\nTexto Decifrado " + Cifrado.DescifradoTexto(texto);
            }
            catch (Exception ex)
            {
                this.txtResult.Text = "Error :" + ex.Message;
            }
        }
Exemplo n.º 24
0
 public ActionResult AltaUsuarios(usuarios_axsis usuarios)
 {
     if (ModelState.IsValid)
     {
         using (BD_CRUD_AxsisEntities db = new BD_CRUD_AxsisEntities())
         {
             if (!db.usuarios_axsis.Any(x => x.usuario == usuarios.usuario))
             {
                 usuarios.fecha_creacion     = DateTime.Now; //insertar fecha inicial al llegar aqui
                 usuarios.estatus            = true;         //inicializarlo en true
                 usuarios.contrasena         = Cifrado.ComputeHash(usuarios.contrasena, "SHA512", GetBytes("MyDemo"));
                 usuarios.contrasena_confirm = Cifrado.ComputeHash(usuarios.contrasena_confirm, "SHA512", GetBytes("MyDemo"));
                 db.usuarios_axsis.Add(usuarios); //agregar los datos al modelo
                 db.SaveChanges();
                 return(RedirectToAction("Index"));
             }
             else
             {
                 ViewBag.UsuarioExiste = "Este usuario ya existe";
             }
         }
     }
     return(View(usuarios));
 }
Exemplo n.º 25
0
        public void DecriptCriptografia()
        {
            string decifrado = "";

            for (int i = 0; i < Cifrado.Length; i++)
            {
                char[] letra       = Cifrado.Substring(i, 1).ToCharArray();
                int    letraMinima = letraInicial + Numero_Casas;
                int    valorLetra  = letra[0];
                if (valorLetra >= letraInicial && valorLetra <= letraFinal)
                {
                    if (valorLetra < letraMinima)
                    {
                        valorLetra = letraFinal + 1 - (letraMinima - valorLetra);
                    }
                    else
                    {
                        valorLetra -= Numero_Casas;
                    }
                }
                decifrado += Char.ConvertFromUtf32(valorLetra);
            }
            Decifrado = decifrado;
        }
Exemplo n.º 26
0
        public UnitTest()
        {
            Cifrado loCifrado = new Cifrado(Dapesa.Criptografia.Comun.Definiciones.TipoCifrado.AES);

            this._oDiagnostico = new Diagnostico(new Dapesa.Facturacion.Servicios.Entidades.Diagnostico()
            {
                DirectorioDiagnostico = @"C:\Users\ricardo.melchor\Downloads\errores",
                DirectorioEntrada     = @"C:\Users\ricardo.melchor\Downloads\entrada",
                DirectorioProcesados  = @"C:\Users\ricardo.melchor\Downloads\procesados",
                Mensaje = new Correo()
                {
                    Asunto       = "AVISO IMPORTANTE FACTURA CANCELADA NO PROCESADA ",
                    Credenciales = new Credenciales {
                        Cifrado     = loCifrado,
                        Contrasenia = loCifrado.Cifrar("mensajero"),
                        Usuario     = "*****@*****.**"
                    },
                    Destinatario = "*****@*****.**",
                    Puerto       = 25,
                    Remitente    = "*****@*****.**",
                    Servidor     = "smtp.dapesa.com.mx"
                }
            });
        }
Exemplo n.º 27
0
        public static ResultLogueo Login(string pUsuario, string pClave, bool pRecordar)
        {
            try
            {
                Cifrado         Security = new Cifrado();
                CarteraEntities db       = new CarteraEntities();

                //Esta variable almacena la clave cifrada pra crear la cokie con los valores ingresados del usuario
                string           pass    = Security.Encriptar(pClave);
                seguridadusuario Usuario = db.seguridadusuarios.Where(u => u.Email == pUsuario).SingleOrDefault();
                if (Usuario != null && Usuario.Clave != pass)
                {
                    Usuario = null;
                }
                if (Usuario != null)
                {
                    if (Usuario.Activo)
                    {
                        //Usuario.tcuentas = db.tcuentas.Where(m => m.Id_Usuario == Usuario.Id && m.Activo).ToList();
                        Parametro.CrearSesionPagina(Usuario);
                        if (pRecordar)
                        {
                            //Creo la cokie para mantener la session;
                            try
                            {
                                LoginViewModel UsuarioCookie = new LoginViewModel
                                {
                                    RememberMe = true,
                                    Email      = Usuario.Email,
                                    Password   = pClave
                                };
                                string User = JsonConvert.SerializeObject(UsuarioCookie);
                                User = Security.Encriptar(User);
                                HttpCookie cookie = new HttpCookie("SSLayerUser")
                                {
                                    Value = User
                                };
                                cookie.Expires.AddDays(10);
                                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                        return(ResultLogueo.Logueo);
                    }
                    else
                    {
                        return(ResultLogueo.Desactivado);
                    }
                }
                else
                {
                    return(ResultLogueo.Invalido);
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return(ResultLogueo.Error);
            }
        }
Exemplo n.º 28
0
        public _ResponsePagarServicios PagarServicio(RequestPagarServicios requestPagarServicios)
        {
            _ResponsePagarServicios responsePagarServicios = null;

            try
            {
                if (!(requestPagarServicios.TipoFront == 1 || requestPagarServicios.TipoFront == 2))
                {
                    _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                    exceptionPagarServicios.Codigo  = -1;
                    exceptionPagarServicios.Mensaje = "El tipo front no corresponde a este servicio";
                    throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "Error personalizado por CMV", new FaultCode("-1"));
                }

                String result = string.Empty;
                responsePagarServicios = new _ResponsePagarServicios();

                // throw new WebException();

                result = PagarServicioJWT(requestPagarServicios, sendTx);


                /*  Para consumir a GestoPago antes de implementar JWT
                 *  responsePagarServicios.request = ParametrosConfig() + requestPagarServicios.ObtenerParametros();
                 *  byte[] data = UTF8Encoding.UTF8.GetBytes(ParametrosConfig() + requestPagarServicios.ObtenerParametros());
                 *  HttpWebRequest request = initRequest(data, abonar);
                 *  Stream postStream = request.GetRequestStream();
                 *  postStream.Write(data, 0, data.Length);
                 *  HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                 *  StreamReader readerResponse = new StreamReader(response.GetResponseStream());
                 *  result = readerResponse.ReadToEnd();
                 */

                responsePagarServicios.response = result;
                if (!string.IsNullOrEmpty(result))
                {
                    new Logg().Warning("xml respuesta :" + result.ToString());
                    ResponseAbonar responseAbonar = SerializerManager <ResponseGeneral> .DeseralizarStringXMLToObject(result).ResponseAbonar;

                    responsePagarServicios.request        = "Metodo: " + sendTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);
                    responsePagarServicios.signed         = Cifrado.CifradoTexto(Uri.EscapeDataString(JsonConvert.SerializeObject(requestPagarServicios)));
                    responsePagarServicios.ResponseAbonar = responseAbonar;
                    responsePagarServicios.EstatusCmv     = EstatusCMV.Ok;
                    responsePagarServicios.MensajeCmv     = "OK";

                    return(responsePagarServicios);
                }
            }
            catch (FaultException <_ExceptionPagarServicios> ex)
            {
                throw ex;
            }
            catch (WebException e)
            {
                new Logg().Error("Error :" + e.ToString());
                responsePagarServicios            = new _ResponsePagarServicios();
                responsePagarServicios.request    = "Metodo: " + sendTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);
                responsePagarServicios.signed     = Cifrado.CifradoTexto(Uri.EscapeDataString(JsonConvert.SerializeObject(requestPagarServicios)));
                responsePagarServicios.EstatusCmv = EstatusCMV.Error;
                responsePagarServicios.MensajeCmv = e.Message + "|" + e.StackTrace;
                //return responsePagarServicios;

                _ResponseConfirmaTransaccion responseConfirmaTransaccion = ConfirmaTransaccion(requestPagarServicios);
                responseConfirmaTransaccion.ResponseAbonar.MENSAJE.CODIGO = responseConfirmaTransaccion.ResponseAbonar.MENSAJE.CODIGO == "06" ? "01" : responseConfirmaTransaccion.ResponseAbonar.MENSAJE.CODIGO;
                Mapper.Initialize(x => { x.CreateMap <_ResponseConfirmaTransaccion, _ResponsePagarServicios>(); });
                responsePagarServicios = Mapper.Map <_ResponsePagarServicios>(responseConfirmaTransaccion);
                return(responsePagarServicios);
            }
            catch (Exception ex)
            {
                _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                exceptionPagarServicios.Codigo  = 1000;//Error no definido p
                exceptionPagarServicios.Mensaje = ex.Message;
                throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "Error personalizado por Exception", new FaultCode("-1"));
            }
            return(null);
        }
Exemplo n.º 29
0
        public _ResponseConfirmaTransaccion ConfirmaTransaccion(RequestPagarServicios requestPagarServicios)
        {
            bool intento = true;
            _ResponseConfirmaTransaccion responseConfirmaTransaccion = null;

            try
            {
                if (!(requestPagarServicios.TipoFront == 1 || requestPagarServicios.TipoFront == 2))
                {
                    _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                    exceptionPagarServicios.Codigo  = -1;
                    exceptionPagarServicios.Mensaje = "El tipo front no corresponde a este servicio";
                    throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "Error personalizado por CMV", new FaultCode("-1"));
                }

                String result = string.Empty;
                responseConfirmaTransaccion = new _ResponseConfirmaTransaccion();


                result = PagarServicioJWT(requestPagarServicios, confirmTx);

                /*
                 * responseConfirmaTransaccion.request = ParametrosConfig() + requestPagarServicios.ObtenerParametros();
                 * byte[] data = UTF8Encoding.UTF8.GetBytes(ParametrosConfig() + requestPagarServicios.ObtenerParametros());
                 *
                 * HttpWebRequest request = initRequest(data,confirmaTransaccion);
                 * Stream postStream = request.GetRequestStream();
                 * postStream.Write(data, 0, data.Length);
                 *
                 * HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                 * StreamReader readerResponse = new StreamReader(response.GetResponseStream());
                 *
                 * result = readerResponse.ReadToEnd();
                 */
                responseConfirmaTransaccion.response = result;
                if (!string.IsNullOrEmpty(result))
                {
                    responseConfirmaTransaccion.request = "Metodo: " + confirmTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);
                    responseConfirmaTransaccion.signed  = Cifrado.CifradoTexto(Uri.EscapeDataString(JsonConvert.SerializeObject(requestPagarServicios)));
                    ResponseAbonar responseAbonar = SerializerManager <ResponseAbonar> .DeseralizarStringToObject(result);

                    responseConfirmaTransaccion.EstatusCmv     = EstatusCMV.Ok;
                    responseConfirmaTransaccion.MensajeCmv     = "Pago realizado Exitosamente";
                    responseConfirmaTransaccion.ResponseAbonar = responseAbonar;
                    return(responseConfirmaTransaccion);
                }
            }
            catch (WebException e)
            {
                responseConfirmaTransaccion.request    = "Metodo: " + confirmTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);
                responseConfirmaTransaccion.signed     = Cifrado.CifradoTexto(Uri.EscapeDataString(JsonConvert.SerializeObject(requestPagarServicios)));
                responseConfirmaTransaccion.EstatusCmv = EstatusCMV.Error;
                responseConfirmaTransaccion.MensajeCmv = e.Message + " | " + e.StackTrace;
                return(responseConfirmaTransaccion);
            }
            catch (FaultException <_ExceptionPagarServicios> ex)
            {
                throw ex;
            }

            catch (Exception ex)
            {
                _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                exceptionPagarServicios.Codigo  = -1;
                exceptionPagarServicios.Mensaje = ex.Message;
                throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "CMV: Error personalizado por Exception", new FaultCode("-1"));
            }
            return(null);
        }
Exemplo n.º 30
0
        public _ResponseConsultaSaldo ConsultarSaldoSerivicio(RequestPagarServicios requestPagarServicios)
        {
            _ResponseConsultaSaldo responseConsultaSaldo = null;

            try
            {
                if (requestPagarServicios.TipoFront != 4)
                {
                    _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                    exceptionPagarServicios.Codigo  = -1;
                    exceptionPagarServicios.Mensaje = "El tipo front no corresponde a este servicio";
                    throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "Error personalizado por CMV", new FaultCode("-1"));
                }

                String result = string.Empty;
                responseConsultaSaldo = new _ResponseConsultaSaldo();
                result = PagarServicioJWT(requestPagarServicios, sendTx);

                /*
                 * responseConsultaSaldo.request = ParametrosConfig() + requestPagarServicios.ObtenerParametros();
                 * byte[] data = UTF8Encoding.UTF8.GetBytes(ParametrosConfig() + requestPagarServicios.ObtenerParametros());
                 * HttpWebRequest request = initRequest(data, abonar);
                 *
                 * Stream postStream = request.GetRequestStream();
                 * postStream.Write(data, 0, data.Length);
                 *
                 * HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                 * StreamReader readerResponse = new StreamReader(response.GetResponseStream());
                 * result = readerResponse.ReadToEnd();
                 */
                responseConsultaSaldo.response = result;
                if (!string.IsNullOrEmpty(result))
                {
                    new Logg().Info("xml respuesta :" + result.ToString());
                    ResponseAbonar responseAbonar = SerializerManager <ResponseGeneral> .DeseralizarStringXMLToObject(result).ResponseAbonar;

                    responseConsultaSaldo.request = "Metodo: " + sendTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);

                    responseConsultaSaldo.ResponseAbonar = responseAbonar;
                    responseConsultaSaldo.EstatusCmv     = EstatusCMV.Ok;
                    responseConsultaSaldo.MensajeCmv     = "Ejecución exitosa del servicio de consultar saldo";
                    responseConsultaSaldo.Signed         = Cifrado.CifradoTexto(Uri.EscapeDataString(JsonConvert.SerializeObject(requestPagarServicios)));
                    return(responseConsultaSaldo);
                }
            }
            catch (FaultException <_ExceptionPagarServicios> ex)
            {
                throw ex;
            }
            catch (WebException e)
            {
                responseConsultaSaldo.request    = "Metodo: " + sendTx + ConexionAPI.ObtenerConexion() + " | " + JsonConvert.SerializeObject(requestPagarServicios);
                responseConsultaSaldo.EstatusCmv = EstatusCMV.Error;
                responseConsultaSaldo.MensajeCmv = e.Message + " | " + e.StackTrace;
                return(responseConsultaSaldo);
            }

            catch (Exception ex)
            {
                _ExceptionPagarServicios exceptionPagarServicios = new _ExceptionPagarServicios();
                exceptionPagarServicios.Codigo  = -1;
                exceptionPagarServicios.Mensaje = ex.Message;
                throw new FaultException <_ExceptionPagarServicios>(exceptionPagarServicios, "Error personalizado por Exception | " + ex.Message, new FaultCode("-1"));
            }
            return(null);
        }