예제 #1
0
        public void CreateAndCompareHashBytes()
        {
            byte[] hash   = Cryptographer.CreateHash(hashInstance, plainTextBytes);
            bool   result = Cryptographer.CompareHash(hashInstance, plainTextBytes, hash);

            Assert.IsTrue(result);
        }
        /// <summary>
        /// Verifies that the specified password matches this users password.
        /// </summary>
        /// <param name="password">The password to check.</param>
        /// <returns>
        /// true if the specified password are valid; otherwise, false.
        /// </returns>
        public bool ValidatePassword(string password)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            bool validPassword = Cryptographer.CompareHash("SHA512", password, this.user.Password);

            if (validPassword && this.IsApproved)
            {
                this.user.LoginAttemptCount = 0;
                this.user.LastLogin         = DateTime.UtcNow;

                // Save database changes
                db.SaveChanges();
                return(true);
            }
            else if (!this.IsLockedOut)
            {
                this.user.LoginAttemptCount += 1;

                // If login attempts reaches 3, we start adding a delay to the login process
                // This is to prevent brute forcing login passwords
                if (this.user.LoginAttemptCount >= 3)
                {
                    // Make the user disabled in the database right now, to prevent attacks
                    // from simply ending the connection if the login takes too long
                    this.user.Active = false;
                    db.SaveChanges();

                    try
                    {
                        // The delay increases for every login attempt
                        // 3rd failed login 4 sec delay
                        // 4th failed login 8 sec delay
                        // 5th failed login 16 sec delay
                        // ...
                        // 10th failed login 512 sec delay
                        Thread.Sleep(1000 * (int)Math.Pow(2, this.user.LoginAttemptCount - 1));
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        Dictionary <string, object> props = new Dictionary <string, object>
                        {
                            { "Error", ex },
                            { "UserId", this.user.UserId },
                            { "LoginAttemptCount", this.user.LoginAttemptCount }
                        };
                        Logger.Write("Exception when delaying login", "Business Object", 600, 0, TraceEventType.Error, "Exception in CosmoMongerMembershipUser.ValidatePassword", props);
                    }

                    // Re-enable the user
                    this.user.Active = true;
                }

                // Save database changes
                db.SaveChanges();
            }

            return(false);
        }
예제 #3
0
        public void CreateAndCompareHashString()
        {
            string hashString = Cryptographer.CreateHash(hashInstance, plainTextString);

            bool result = Cryptographer.CompareHash(hashInstance, plainTextString, hashString);

            Assert.IsTrue(result);
        }
예제 #4
0
        public void CreateAndCompareInvalidHashBytes()
        {
            byte[] hash = Cryptographer.CreateHash(hashInstance, plainTextBytes);

            byte[] badPlainText = new byte[] { 2, 1, 0 };
            bool   result       = Cryptographer.CompareHash(hashInstance, badPlainText, hash);

            Assert.IsFalse(result);
        }
예제 #5
0
        /// <summary>
        /// Ingresar Usuario y Password
        /// </summary>
        /// <param name="usuario"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int DB_verifica(string usuario, string password)
        {
            DA_AdminUser da = new DA_AdminUser();
            //DataTable dt = new DataTable();
            //dt = da.DA_verifica(usuario);

            //REALIZA CIFRADO DE CLAVES DE USUARIOS
            //lrojas:19-05-2016
            DataTable dt      = new DataTable();
            int       Id_User = 0;

            try
            {
                dt = da.DA_verifica(usuario);
                //string aux = dt.Rows[0][0].ToString();
                if (dt.Rows.Count == 0)
                {
                    Id_User = -3;
                    return(Id_User);
                }
                if (dt.Rows[0]["Id_Usuario"].ToString() == usuario)
                {
                    //if (dt.Rows[0][5].ToString() == password)
                    string pass_obtenido = dt.Rows[0]["Clave"].ToString();
                    if (Cryptographer.CompareHash(hashProvider, password, pass_obtenido))
                    {
                        if (dt.Rows[0]["Estado"].ToString() == "HABILITADO")
                        {
                            Id_User = 1;
                        }
                        else
                        {
                            Id_User = -1;
                            //lblError.Text = "ERROR NO ES UN USUARIO VALIDO O FUE DADO DE BAJA";
                        }
                    }
                    else
                    {
                        Id_User = -2;
                        //lblError.Text = " ERROR EN LA CONTRASEÑA";
                    }
                }
                else
                {
                    Id_User = -3;
                    //lblError.Text = " ERROR EN EL CODIGO";
                }
                return(Id_User);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //
            //return Id_User;
        }
예제 #6
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public static bool CompareHash(string mensagemoriginal, string mensagemencriptada)
 {
     if (Cryptographer.CompareHash("SHA1Managed", mensagemoriginal, mensagemencriptada))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        private bool CompareHash(string plainText, byte[] existingHashValue)
        {
            byte[] valueToHash = System.Text.Encoding.UTF8.GetBytes(plainText);

            bool matched = Cryptographer.CompareHash(hashProvider, valueToHash, existingHashValue);

            // Clear the byte array memory
            Array.Clear(valueToHash, 0, valueToHash.Length);

            return(matched);
        }
예제 #8
0
        protected void btCambiar_Click(object sender, EventArgs e)
        {
            try
            {
                DB_AdminUser db            = new DB_AdminUser();
                Usuario      ObjUsuario    = new Usuario();
                string       pass_obtenido = VS_Usuario.Clave;

                if (Cryptographer.CompareHash(hashProvider, txt_Contrasena_Antigua.Text, pass_obtenido))
                {
                    if (txt_Contrasena.Text.Trim() != string.Empty)
                    {
                        if (txt_Contrasena.Text.Trim() == txt_Repetir_Contrasena.Text.Trim())
                        {
                            ObjUsuario       = VS_Usuario;
                            ObjUsuario.Clave = txt_Contrasena.Text.Trim();
                            db.DB_Usuario_Perfil_Actualizar(ObjUsuario);
                            db.DB_Registra_Log_Password(ObjUsuario.Id_Usuario, txt_Id_Usuario.Text);//LROJAS:07/10/2016
                            Session["idUser"] = null;
                            Session.Abandon();
                            Response.Redirect("~/Default.aspx", true);
                        }
                        else
                        {
                            lblError.Text = "Contraseñas no Coinciden";
                            txt_Contrasena.Focus();
                        }
                    }
                    else
                    {
                        lblError.Text = "Ingrese Contraseña";
                        txt_Contrasena.Focus();
                    }
                }
                else
                {
                    lblError.Text = "Contraseña Incorrecta";
                    txt_Contrasena_Antigua.Focus();
                    //txt_Contrasena_Antigua.BackColor = System.Drawing.Color.Tomato;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
예제 #9
0
        // App.config中添加hashProviders节点
        static void test1()
        {
            //获取离散码
            string hash = Cryptographer.CreateHash("MD5Cng", "SensitiveData");

            Console.WriteLine(hash);

            Console.WriteLine("-------------------------------------------------");

            bool equal = Cryptographer.CompareHash("MD5Cng", "SensitiveData", hash);

            if (equal)
            {
                Console.WriteLine("正确");
            }
            else
            {
                Console.WriteLine("错误");
            }
        }
예제 #10
0
        public UserEntity FindByPasswordCredential(string login, string password)
        {
            Contract.Assert(login != null);
            Contract.Assert(password != null);
            UserEntity user       = null;
            var        credential = this.Repository.FindOne(new UserPasswordCredentialByLogin(login));

            if (credential != null)
            {
                var saltedPassword = GetSaltedPassword(password, credential.PasswordSalt);
                if (Cryptographer.CompareHash(HashInstance, saltedPassword, credential.PasswordHash))
                {
                    if (credential.User != null && !credential.User.Deleted)
                    {
                        user = credential.User;
                    }
                }
            }

            return(user);
        }
예제 #11
0
        public static void Main()
        {
            Console.WriteLine("Enter string to encrypt:");
            string stringToEncrypt = Console.ReadLine();

            // encrypt
            byte[] valueToEncrypt    = Encoding.Unicode.GetBytes(stringToEncrypt);
            byte[] encryptedContents = Cryptographer.EncryptSymmetric("My DPAPI Symmetric Cryptography Provider", valueToEncrypt);

            string stringToDecrypt = (new UnicodeEncoding()).GetString(encryptedContents);

            Console.WriteLine("Encrypted as \"{0}\"", stringToDecrypt);

            // decrypt
            byte[] valueToDecrypt    = Encoding.Unicode.GetBytes(stringToDecrypt);
            byte[] decryptedContents = Cryptographer.DecryptSymmetric("My DPAPI Symmetric Cryptography Provider", valueToDecrypt);
            string plainText         = (new UnicodeEncoding()).GetString(decryptedContents);

            Console.WriteLine("Decrypted to \"{0}\"", plainText);

            // hashing
            string stringValueToHash = "password";

            byte[] valueToHash   = (new UnicodeEncoding()).GetBytes(stringValueToHash);
            byte[] generatedHash = Cryptographer.CreateHash("MySHA1Managed", valueToHash);
            string hashString    = (new UnicodeEncoding()).GetString(generatedHash);

            Console.WriteLine("Hash of \"{0}\" is \"{1}\"", stringValueToHash, hashString);

            byte[] stringToCompare     = (new UnicodeEncoding()).GetBytes(stringValueToHash);
            bool   comparisonSucceeded = Cryptographer.CompareHash("MySHA1Managed", stringToCompare, generatedHash);

            Console.WriteLine("\"{0}\" hashes to \"{1}\" = {2} ", stringValueToHash, hashString, comparisonSucceeded);

            Console.Read();
        }
예제 #12
0
 /// <summary>
 /// 判断HASH字符串是否相等
 /// </summary>
 /// <param name="hashName">HASH加密方式</param>
 /// <param name="decryptData">加密字符串</param>
 /// <param name="encrytData">解密字符串</param>
 /// <returns>是否相等</returns>
 public static bool CompareHash(string hashName, string decryptData, string encrytData)
 {
     return(Cryptographer.CompareHash(hashName, decryptData, encrytData));
 }
예제 #13
0
 /// <summary>
 /// Compara o hash informado.
 /// </summary>
 /// <param name="plaintext">Texto informado pela interface.</param>
 /// <param name="hash">Hash salvo.</param>
 /// <returns>True ou False para a comparação.</returns>
 public static bool CompareHash(string plaintext, string hash)
 {
     return(Cryptographer.CompareHash("SHA1Managed", plaintext.ToLower(), hash));
 }
예제 #14
0
 public bool CompareHashOnMD5Cng(string plainValue, string hash)
 {
     return(Cryptographer.CompareHash("MD5CngCrypto", plainValue, hash));
 }
예제 #15
0
        public void CompareHashWithZeroLengthInstanceString()
        {
            string hash = Cryptographer.CreateHash(hashInstance, plainTextString, context);

            Cryptographer.CompareHash(string.Empty, plainTextString, hash);
        }
예제 #16
0
        public void CompareHashWithNullInstanceString()
        {
            string hash = Cryptographer.CreateHash(hashInstance, plainTextString, context);

            Cryptographer.CompareHash(null, plainTextString, hash);
        }
예제 #17
0
 public void CompareHashWithZeroLengthInstance()
 {
     byte[] hash = Cryptographer.CreateHash(hashInstance, plainTextBytes, context);
     Cryptographer.CompareHash(string.Empty, plainTextBytes, hash);
 }
예제 #18
0
 public void CompareHashWithNullInstance()
 {
     byte[] hash = Cryptographer.CreateHash(hashInstance, plainTextBytes, context);
     Cryptographer.CompareHash(null, plainTextBytes, hash);
 }
예제 #19
0
 public void CompareHashWithInvalidString()
 {
     Cryptographer.CompareHash(hashInstance, plainTextString, "INVALID", context);
 }
예제 #20
0
 public static bool SHACompareHash(string plainText, string hashedText)
 {
     return(Cryptographer.CompareHash(SHAProviderName, plainText, hashedText));
 }
예제 #21
0
 public bool CompareHash(string plainText, string hashedText)
 {
     return(Cryptographer.CompareHash("HashProvider", plainText, hashedText, this.ConfigurationContext));
 }
예제 #22
0
 public static bool CompareHash(string plainText, string hashedText)
 {
     return(Cryptographer.CompareHash("hashprovider", plainText, hashedText));
 }
예제 #23
0
        private bool ValidateUser()
        {
            bool IsAuthenticated = false;

            DataCommandService dataCommandDB = DataCommandService.GetInstance();
            PageDB             pageDB        = new PageDB();
            DataTable          data          = null;
            string             password      = String.Empty;

            List <ScreenDataCommandParameter> parameters = pageDB.GetPopulatedCommandParameters(Me.ProfileCommand, Page);

            foreach (ScreenDataCommandParameter p in parameters)
            {
                if (p.Name.ToLower() == Me.UserNameParameter.ToLower())
                {
                    LoginName = Page.GetEntityIDValue(Page.Screen, p.InputKey, p.InputType);
                    break;
                }
            }
            password = Page.GetEntityIDValue(Page.Screen, Me.PasswordEntityID, Me.PasswordEntityInputType);

            data = dataCommandDB.GetDataForDataCommand(Me.ProfileCommand, parameters);

            if (data.Rows.Count == 1)
            {
                profile = data.Rows[0];
                string dbPassword = profile[Me.PasswordField].ToString();

                PasswordMode mode = Me.PasswordMode;

                if (!String.IsNullOrEmpty(dbPassword))
                {
                    switch (mode)
                    {
                    case PasswordMode.Hash:
                        if (Cryptographer.CompareHash(Me.PasswordAlgorithm, password, dbPassword))
                        {
                            IsAuthenticated = true;
                        }



                        break;

                    case PasswordMode.Encrypted:
                        string decryptedPassword = Cryptographer.DecryptSymmetric(Me.PasswordAlgorithm, dbPassword);
                        if (decryptedPassword == password)
                        {
                            IsAuthenticated = true;
                        }
                        break;

                    case PasswordMode.PlainText:
                        if (dbPassword == password)
                        {
                            IsAuthenticated = true;
                        }
                        break;
                    }
                }
            }

            return(IsAuthenticated);
        }
예제 #24
0
 public static bool CompararHash(string textoProbar, string textoHash)
 {
     return(Cryptographer.CompareHash(HashProviderName, textoProbar, textoHash));
 }
예제 #25
0
 public static bool SHACompareHash(byte[] plainText, byte[] hashedText)
 {
     return(Cryptographer.CompareHash(SHAProviderName, plainText, hashedText));
 }