/// <summary>Hash a password using the OpenBSD bcrypt scheme.</summary>
        /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
        ///                                     illegal values.</exception>
        /// <param name="input">The password to hash.</param>
        /// <param name="salt">    the salt to hash with (perhaps generated using BCrypt.gensalt).</param>
        /// <returns>The hashed password</returns>
        public static string HashPassword(string input, string salt)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (string.IsNullOrEmpty(salt))
            {
                throw new ArgumentException("Invalid salt", "salt");
            }

            // Determinthe starting offset and validate the salt
            int  startingOffset;
            char minor = (char)0;

            if (salt[0] != '$' || salt[1] != '2')
            {
                throw new SaltParseException("Invalid salt version");
            }
            if (salt[2] == '$')
            {
                startingOffset = 3;
            }
            else
            {
                minor = salt[2];
                if (minor != 'a' || salt[3] != '$')
                {
                    throw new SaltParseException("Invalid salt revision");
                }
                startingOffset = 4;
            }

            // Extract number of rounds
            if (salt[startingOffset + 2] > '$')
            {
                throw new SaltParseException("Missing salt rounds");
            }

            // Extract details from salt
            int    logRounds     = Convert.ToInt32(salt.Substring(startingOffset, 2));
            string extractedSalt = salt.Substring(startingOffset + 3, 22);

            byte[] inputBytes = Encoding.UTF8.GetBytes((input + (minor >= 'a' ? "\0" : "")));
            byte[] saltBytes  = DecodeBase64(extractedSalt, BCRYPT_SALT_LEN);

            BCrypt bCrypt = new BCrypt();

            byte[] hashed = bCrypt.CryptRaw(inputBytes, saltBytes, logRounds);

            // Generate result string
            StringBuilder result = new StringBuilder();

            result.Append("$2");
            if (minor >= 'a')
            {
                result.Append(minor);
            }
            result.AppendFormat("${0:00}$", logRounds);
            result.Append(EncodeBase64(saltBytes, saltBytes.Length));
            result.Append(EncodeBase64(hashed, (_BfCryptCiphertext.Length * 4) - 1));
            return(result.ToString());
        }
Exemple #2
0
        protected void btnRegistrar_Click(object sender, EventArgs e)
        {
            try {
                if (txtNombre.Text != string.Empty && txtPassword.Text != string.Empty && txtConfirmar.Text != string.Empty)
                {
                    Modelo.Usuario usuario = new Modelo.Usuario();
                    usuario.NOMBRE_USUARIO = txtNombre.Text;
                    string hashed = BCrypt.HashPassword(txtPassword.Text, BCrypt.GenerateSalt(12));
                    usuario.PASSWORD     = hashed;
                    usuario.ESTADO       = Modelo.Estado_Usuario.Habilitado.ToString();
                    usuario.TIPO_USUARIO = Modelo.Tipo_Usuario.Cliente.ToString();

                    Service1      s      = new Service1();
                    XmlSerializer sr     = new XmlSerializer(typeof(Modelo.Usuario));
                    StringWriter  writer = new StringWriter();
                    sr.Serialize(writer, usuario);

                    if (txtPassword.Text.Equals(txtConfirmar.Text))
                    {
                        if (!s.ExisteUsuario(writer.ToString()))
                        {
                            if (txtRut.Text != string.Empty && txtNombreC.Text != string.Empty && txtDireccion.Text != string.Empty)
                            {
                                int telefono = 0;

                                if (txtTelefono.Text == string.Empty)
                                {
                                    Modelo.Cliente   cliente   = new Modelo.Cliente();
                                    Modelo.Proveedor proveedor = new Modelo.Proveedor();
                                    Modelo.Empleado  empleado  = new Modelo.Empleado();

                                    cliente.RUT_CLIENTE     = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));
                                    proveedor.RUT_PROVEEDOR = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));
                                    empleado.RUT_EMPLEADO   = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));

                                    cliente.ID_COMUNA         = short.Parse(ddlComuna.SelectedValue);
                                    cliente.DV_CLIENTE        = txtRut.Text.Substring(txtRut.Text.Length - 1);
                                    cliente.DIRECCION_CLIENTE = txtDireccion.Text;
                                    cliente.NOMBRE_CLIENTE    = txtNombreC.Text;
                                    if (txtEmail.Text == string.Empty)
                                    {
                                        cliente.CORREO_CLIENTE = "";
                                    }
                                    else
                                    {
                                        cliente.CORREO_CLIENTE = txtEmail.Text;
                                    }

                                    cliente.TELEFONO_CLIENTE = telefono;

                                    XmlSerializer sr2     = new XmlSerializer(typeof(Modelo.Cliente));
                                    StringWriter  writer2 = new StringWriter();
                                    sr2.Serialize(writer2, cliente);
                                    writer2.Close();

                                    XmlSerializer sr3     = new XmlSerializer(typeof(Modelo.Proveedor));
                                    StringWriter  writer3 = new StringWriter();
                                    sr3.Serialize(writer3, proveedor);
                                    writer3.Close();

                                    XmlSerializer sr4     = new XmlSerializer(typeof(Modelo.Empleado));
                                    StringWriter  writer4 = new StringWriter();
                                    sr4.Serialize(writer4, empleado);
                                    writer4.Close();

                                    if (!s.ExisteRutC(writer2.ToString()) && !s.ExisteRutP(writer3.ToString()) && !s.ExisteRutE(writer4.ToString()))
                                    {
                                        if (s.RegistroUsuario(writer.ToString()) && s.RegistroCliente(writer2.ToString()))
                                        {
                                            Response.Write("<script language='javascript'>window.alert('Se ha registrado con éxito. pruebe iniciar sesión');window.location='../Hostal/WebLogin.aspx';</script>");
                                        }
                                        else
                                        {
                                            error.Text     = "El registro ha fallado";
                                            alerta.Visible = true;
                                        }
                                    }
                                    else
                                    {
                                        error.Text     = "El Rut ya existe";
                                        alerta.Visible = true;
                                    }
                                }
                                else
                                {
                                    if (int.TryParse(txtTelefono.Text, out telefono))
                                    {
                                        Modelo.Cliente   cliente   = new Modelo.Cliente();
                                        Modelo.Proveedor proveedor = new Modelo.Proveedor();
                                        Modelo.Empleado  empleado  = new Modelo.Empleado();

                                        cliente.RUT_CLIENTE     = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));
                                        proveedor.RUT_PROVEEDOR = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));
                                        empleado.RUT_EMPLEADO   = int.Parse(txtRut.Text.Substring(0, txtRut.Text.Length - 2));

                                        cliente.ID_COMUNA         = short.Parse(ddlComuna.SelectedValue);
                                        cliente.DV_CLIENTE        = txtRut.Text.Substring(txtRut.Text.Length - 1);
                                        cliente.DIRECCION_CLIENTE = txtDireccion.Text;
                                        cliente.NOMBRE_CLIENTE    = txtNombreC.Text;
                                        if (txtEmail.Text == string.Empty)
                                        {
                                            cliente.CORREO_CLIENTE = "";
                                        }
                                        else
                                        {
                                            cliente.CORREO_CLIENTE = txtEmail.Text;
                                        }

                                        cliente.TELEFONO_CLIENTE = telefono;

                                        XmlSerializer sr2     = new XmlSerializer(typeof(Modelo.Cliente));
                                        StringWriter  writer2 = new StringWriter();
                                        sr2.Serialize(writer2, cliente);
                                        writer2.Close();

                                        XmlSerializer sr3     = new XmlSerializer(typeof(Modelo.Proveedor));
                                        StringWriter  writer3 = new StringWriter();
                                        sr3.Serialize(writer3, proveedor);
                                        writer3.Close();

                                        XmlSerializer sr4     = new XmlSerializer(typeof(Modelo.Empleado));
                                        StringWriter  writer4 = new StringWriter();
                                        sr4.Serialize(writer4, empleado);
                                        writer4.Close();

                                        if (!s.ExisteRutC(writer2.ToString()) && !s.ExisteRutP(writer3.ToString()) && !s.ExisteRutE(writer4.ToString()))
                                        {
                                            if (s.RegistroUsuario(writer.ToString()) && s.RegistroCliente(writer2.ToString()))
                                            {
                                                //Datos Usuario
                                                txtNombre.Text    = string.Empty;
                                                txtPassword.Text  = string.Empty;
                                                txtConfirmar.Text = string.Empty;

                                                //Datos Cliente
                                                txtRut.Text             = string.Empty;
                                                txtNombreC.Text         = string.Empty;
                                                txtDireccion.Text       = string.Empty;
                                                txtEmail.Text           = string.Empty;
                                                txtTelefono.Text        = string.Empty;
                                                ddlPais.SelectedIndex   = 0;
                                                ddlRegion.SelectedIndex = 0;
                                                ddlComuna.SelectedIndex = 0;

                                                Response.Write("<script language='javascript'>window.alert('Se ha registrado con éxito. pruebe iniciar sesión');window.location='../Hostal/WebLogin.aspx';</script>");
                                            }
                                            else
                                            {
                                                error.Text     = "El registro ha fallado";
                                                alerta.Visible = true;
                                            }
                                        }
                                        else
                                        {
                                            error.Text     = "El Rut ya existe";
                                            alerta.Visible = true;
                                        }
                                    }
                                    else
                                    {
                                        error.Text     = "Verifique que ha ingresado el teléfono correctamente";
                                        alerta.Visible = true;
                                    }
                                }
                            }
                            else
                            {
                                error.Text     = "Verifique que ha ingresados todos los datos requeridos de Cliente";
                                alerta.Visible = true;
                            }
                        }
                        else
                        {
                            error.Text     = "El Nombre de usuario ya ha sido utilizado. Intente con otro";
                            alerta.Visible = true;
                        }
                    }
                    else
                    {
                        error.Text     = "Las Contraseñas no coinciden";
                        alerta.Visible = true;
                    }
                }
                else
                {
                    error.Text     = "Verifique que todos los datos de usuario hayan sido ingresados";
                    alerta.Visible = true;
                }
            }
            catch (Exception) {
                error.Text     = "Excepcion";
                alerta.Visible = true;
            }
        }