protected override byte[] getHash()
 {
     var hashIterations = 24200;
     List<byte> hashList = new List<byte>();
     var hash = new SHA512Managed();
     var hashLength = Math.Max(plaintext.Length, cyphertext.Length);
     while (hashList.Count <= hashLength)
     {
         byte[] hashBytes = hash.ComputeHash(key);
         for (var i = 1; i < hashIterations; i++)
         {
             hashBytes = hash.ComputeHash(hashBytes);
         }
         hashList.AddRange(hashBytes);
     }
     return hashList.ToArray();
 }
示例#2
0
 public static string CreateSHAHash(string Phrase)
 {
     SHA512Managed HashTool = new SHA512Managed();
     Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
     Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
     HashTool.Clear();
     return Convert.ToBase64String(EncryptedBytes);
 }
示例#3
0
    public string Generatehash512(string text)
    {
        byte[] message = Encoding.UTF8.GetBytes(text);

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        SHA512Managed hashString = new SHA512Managed();
        string hex = "";
        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }
示例#4
0
        protected void submit_btn_Click(object sender, EventArgs e)
        {
            DBServiceReference1.Service1Client client = new DBServiceReference1.Service1Client();
            error_lb.Text = "";
            bool   pass      = true;  // overall validation
            bool   mt        = false; // empty check
            string salt      = "";
            string hashednew = "";

            // checking if any fields are empty
            if (String.IsNullOrWhiteSpace(current_tb.Text) || String.IsNullOrWhiteSpace(new_tb.Text) || String.IsNullOrWhiteSpace(new2_tb.Text))
            {
                error_lb.Text = "Please fill all fields. <br>";
                mt            = true;
            }

            if (!mt)
            {
                // checks if user exists
                var user = client.SelectByEmail(Session["LoggedIn"].ToString());

                // initializing hashing thingy
                SHA512Managed hashing = new SHA512Managed();

                // salting plaintext and hashing after
                salt = user.Password_Salt;
                string saltedpw = current_tb.Text.Trim() + salt;
                string hashedpw = Convert.ToBase64String(hashing.ComputeHash(Encoding.UTF8.GetBytes(saltedpw)));

                if (hashedpw != user.Password)
                {
                    error_lb.Text = error_lb.Text + "Incorrect password <br>";
                    pass          = false;
                }

                string saltednew = new_tb.Text.Trim() + salt;
                hashednew = Convert.ToBase64String(hashing.ComputeHash(Encoding.UTF8.GetBytes(saltednew)));
                if (hashednew == user.Password || hashednew == user.Password_Last1 || hashednew == user.Password_Last2)
                {
                    error_lb.Text = error_lb.Text + "New password cannot be the same as current or previous 2 passwords <br>";
                    pass          = false;
                }

                Regex pwRegex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}");
                if (!pwRegex.IsMatch(new_tb.Text.Trim()))
                {
                    error_lb.Text = error_lb.Text + "Please input a password that fulfills all criteria <br>";
                    pass          = false;
                }

                TimeSpan span = DateTime.Now.Subtract(user.Password_Age);
                if (Convert.ToInt16(span.TotalMinutes) <= 5)
                {
                    error_lb.Text = error_lb.Text + "You must wait " + (5 - Convert.ToInt16(span.TotalMinutes)).ToString() + " more minutes to change your password <br>";
                    pass          = false;
                }
            }

            if (!mt && pass)
            {
                int result = client.ChangePassword(Session["LoggedIn"].ToString(), hashednew);
                if (result == 1)
                {
                    Session.Clear();
                    Session.Abandon();
                    Session.RemoveAll();

                    Response.Redirect("Login.aspx");

                    if (Request.Cookies["ASP.NET_SessionId"] != null)
                    {
                        Response.Cookies["ASP.NET_SessionId"].Value   = string.Empty;
                        Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                    }

                    if (Request.Cookies["AuthToken"] != null)
                    {
                        Response.Cookies["AuthToken"].Value   = string.Empty;
                        Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                    }
                }
                else
                {
                    error_lb.Text = "Unable to change password. Please try again later.";
                }
            }
        }
示例#5
0
        protected void btn_login_Click(object sender, EventArgs e)
        {
            if (CaptchaValidation())
            {
                string        pword = HttpUtility.HtmlEncode(tb_password.Text.ToString().Trim());
                string        email = HttpUtility.HtmlEncode(tb_email.Text.ToString().Trim());
                SHA512Managed hashh = new SHA512Managed();
                string        dbh   = getDBH(email);
                string        dbs   = getDBS(email);

                Session["Error"] = "Email or password is invalid, try again";
                if (statCheck(email) == "1")
                {
                    if (timeDiff(email) < 15)
                    {
                        try
                        {
                            if (dbs != null && dbs.Length > 0 && dbh != null && dbh.Length > 0)
                            {
                                string pwordWithSalt = pword + dbs;
                                byte[] hashWithSalt  = hashh.ComputeHash(Encoding.UTF8.GetBytes(pwordWithSalt));
                                string emailHash     = Convert.ToBase64String(hashWithSalt);

                                if (emailHash.Equals(dbh))
                                {
                                    Session["IsLoggedIn"] = tb_email.Text.Trim();

                                    string guid = Guid.NewGuid().ToString();
                                    Session["AuthenticationToken"] = guid;

                                    Response.Cookies.Add(new HttpCookie("AuthenticationToken", guid));

                                    Response.Redirect("AfterLogin.aspx?email=" + HttpUtility.HtmlEncode(email), false);
                                }
                                else
                                {
                                    Session["AttemptCount"] = Convert.ToInt32(Session["AttemptCount"]) + 1;
                                    if (Convert.ToInt32(Session["AttemptCount"]) >= 3)
                                    {
                                        AccountLockout(email);
                                    }
                                    else
                                    {
                                        Response.Redirect("Login.aspx?error=error", false);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.ToString());
                        }
                        finally { }
                    }
                    else
                    {
                        lblError.Text              = "Your password has expired, please change your password now.";
                        lblError.ForeColor         = System.Drawing.Color.Red;
                        btn_login.Visible          = false;
                        btn_changePassword.Visible = true;
                    }
                }
                else
                {
                    lblError.Text       = "Your account has been locked out";
                    lblError.ForeColor  = System.Drawing.Color.Red;
                    btn_Recover.Visible = true;
                }
            }
        }
示例#6
0
 /// <summary>
 /// Hashes a byte array through SHA-512.
 /// </summary>
 /// <param name="input">The byte array for which to calculate the hash</param>
 /// <returns>The SHA-512 digest.</returns>
 public static byte[] SHA512(byte[] input)
 {
     using SHA512Managed sha512 = new SHA512Managed();
     return(sha512.ComputeHash(input));
 }
        internal bool InvokeNetGetData(ref byte msgId, MessageBuffer buffer, ref int index, ref int length)
        {
            if (Main.netMode == 2)
            {
                // A critical server crash/slow-down bug was exploited in which a 0-length
                // packet is sent, causing all NetGetData handlers to throw exceptions.
                // Because a packet's header is 2 bytes of length + 1 byte of packet type,
                // all packets must contain at least 3 bytes.
                // Ideally this check should occur in an OTAPI modification.
                if (length < 1)
                {
                    RemoteClient currentClient = Netplay.Clients[buffer.whoAmI];
                    Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                    return(true);
                }

                // A critical server crash/corruption bug was reported by @bartico6 on GitHub.
                // If a packet length comes in at extreme values, the server can enter infinite loops, deadlock, and corrupt the world.
                // As a result, we take the following action: disconnect the player and log the attempt as soon as we can.
                // The length 1000 was chosen as an arbitrarily large number for all packets. It may need to be tuned later.
                if (length > 1000)
                {
                    RemoteClient currentClient = Netplay.Clients[buffer.whoAmI];
                    Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                    return(true);
                }

                switch ((PacketTypes)msgId)
                {
                case PacketTypes.ConnectRequest:
                    if (this.InvokeServerConnect(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.ContinueConnecting2:
                    if (this.InvokeServerJoin(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.LoadNetModule:
                    using (var stream = new MemoryStream(buffer.readBuffer))
                    {
                        stream.Position = index;
                        using (var reader = new BinaryReader(stream))
                        {
                            ushort moduleId = reader.ReadUInt16();
                            //LoadNetModule is now used for sending chat text.
                            //Read the module ID to determine if this is in fact the text module
                            if (moduleId == Terraria.Net.NetManager.Instance.GetId <Terraria.GameContent.NetModules.NetTextModule>())
                            {
                                //Then deserialize the message from the reader
                                Terraria.Chat.ChatMessage msg = Terraria.Chat.ChatMessage.Deserialize(reader);

                                if (InvokeServerChat(buffer, buffer.whoAmI, @msg.Text, msg.CommandId))
                                {
                                    return(true);
                                }
                            }
                        }
                    }

                    break;

                //Making sure packet length is 38, otherwise it's not a valid UUID packet length.
                //We copy the bytes of the UUID then convert it to string. Then validating the GUID so its the correct format.
                //Then the bytes get hashed, and set as ClientUUID (and gets written in DB for auto-login)
                //length minus 2 = 36, the length of a UUID.
                case PacketTypes.ClientUUID:
                    if (length == 38)
                    {
                        byte[] uuid = new byte[length - 2];
                        Buffer.BlockCopy(buffer.readBuffer, index + 1, uuid, 0, length - 2);
                        Guid guid = new Guid();
                        if (Guid.TryParse(Encoding.Default.GetString(uuid, 0, uuid.Length), out guid))
                        {
                            SHA512 shaM   = new SHA512Managed();
                            var    result = shaM.ComputeHash(uuid);
                            Netplay.Clients[buffer.whoAmI].ClientUUID = result.Aggregate("", (s, b) => s + b.ToString("X2"));
                            return(true);
                        }
                    }
                    Netplay.Clients[buffer.whoAmI].ClientUUID = "";
                    return(true);
                }
            }

            GetDataEventArgs args = new GetDataEventArgs
            {
                MsgID  = (PacketTypes)msgId,
                Msg    = buffer,
                Index  = index,
                Length = length
            };

            this.NetGetData.Invoke(args);

            msgId  = (byte)args.MsgID;
            index  = args.Index;
            length = args.Length;
            return(args.Handled);
        }
示例#8
0
        /// <summary>
        /// Accepts plaintext and returns a SHA-512 hash of it.
        /// </summary>
        /// <param name="text">Any text to hash.</param>
        /// <returns>SHA-512 hash of the given text.</returns>
        public string Hash(string text)
        {
            var sha512 = new SHA512Managed();

            return(Regex.Replace(BitConverter.ToString(sha512.ComputeHash(Encoding.Default.GetBytes(text))), "-", "").ToLower());
        }
示例#9
0
    //AIM: THIS FUNCTION IS USE to encrypt the string and create hask key using diff hash methods
    public string FromString(string input, HashType hashtype)
    {
        Byte[] clearBytes;
            Byte[] hashedBytes;
            string output = String.Empty;

            switch (hashtype)
            {
                case HashType.RIPEMD160:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.MD5:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA1:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    sha1.ComputeHash(clearBytes);
                    hashedBytes = sha1.Hash;
                    sha1.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA256:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA256 sha256 = new SHA256Managed();
                    sha256.ComputeHash(clearBytes);
                    hashedBytes =sha256.Hash;

                    sha256.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA384:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA384 sha384 = new SHA384Managed();
                    sha384.ComputeHash(clearBytes);
                    hashedBytes = sha384.Hash;
                    sha384.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA512:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA512 sha512 = new SHA512Managed();
                    sha512.ComputeHash(clearBytes);
                    hashedBytes = sha512.Hash;
                    sha512.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
            }
            return output;
    }
        protected void btn_submit_click(object sender, EventArgs e)
        {
            int    scores = checkPassword(HttpUtility.HtmlEncode(tb_pass.Text));
            string status = "";

            switch (scores)
            {
            case 1:
                status = "Very Weak";
                break;

            case 2:
                status = "Weak";
                break;

            case 3:
                status = "Medium";
                break;

            case 4:
                status = "Strong";
                break;

            case 5:
                status = "Very Strong";
                break;

            default:
                break;
            }
            lb_msg.Text = "Status " + status;
            if (scores < 4)
            {
                lb_msg.ForeColor = Color.Red;
                return;
            }
            lb_msg.ForeColor = Color.Green;
            if (tb_pass.Text == "" || tb_email.Text == "")
            {
                lb_msg.Text      = "Missing Inputs";
                lb_msg.ForeColor = Color.Red;
            }
            else
            {
                var email_check   = "";
                var password_old1 = "";
                var password_old2 = "";
                var status_check  = "";
                var minTime       = DateTime.Now;
                var maxTime       = DateTime.Now;


                var    pass  = HttpUtility.HtmlEncode(tb_pass.Text);
                var    email = HttpUtility.HtmlEncode(tb_email.Text);
                string MYDBConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString;



                try
                {
                    SqlConnection con = new SqlConnection(MYDBConnectionString);
                    con.Open();
                    var        str = "Select * From [user] where email = @email";
                    SqlCommand cmd = new SqlCommand(str, con);
                    cmd.Parameters.AddWithValue("@email", email);
                    SqlDataReader myReader = cmd.ExecuteReader();

                    while (myReader.Read())
                    {
                        // Assuming your desired value is the name as the 3rd field
                        status_check  = myReader.GetValue(8).ToString();
                        password_old1 = myReader.GetValue(5).ToString();
                        password_old2 = myReader.GetValue(6).ToString();
                        email_check   = myReader.GetValue(4).ToString();
                        salt          = myReader.GetValue(7).ToString();
                        minTime       = Convert.ToDateTime(myReader.GetValue(10).ToString());
                        maxTime       = Convert.ToDateTime(myReader.GetValue(11).ToString());
                    }
                    con.Close();
                    con.Open();

                    str = "Update [user] set password = @pass, password_old = @pass2, salt_key = @salt_key, minTime = @minTime, maxTime = @maxTime where email = @email";
                    cmd = new SqlCommand(str, con);
                    cmd.Parameters.AddWithValue("@email", email);

                    string pwd = HttpUtility.HtmlEncode(pass.Trim());

                    SHA512Managed hashing      = new SHA512Managed();
                    string        pwdWithSalt  = pwd + salt;
                    byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
                    byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                    finalHash = Convert.ToBase64String(hashWithSalt);

                    if (DateTime.Now < minTime.AddMinutes(5))
                    {
                        lb_msg.Text      = "Cannot change password so soon";
                        lb_msg.ForeColor = Color.Red;
                    }
                    else
                    {
                        if (finalHash != password_old1 && finalHash != password_old2)
                        {
                            cmd.Parameters.AddWithValue("@pass", finalHash);
                            cmd.Parameters.AddWithValue("@pass2", password_old1);
                            cmd.Parameters.AddWithValue("@salt_key", salt);
                            cmd.Parameters.AddWithValue("@minTime", DateTime.Now);
                            cmd.Parameters.AddWithValue("@maxTime", DateTime.Now.AddMinutes(15));
                            cmd.CommandText = str;
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                        else
                        {
                            lb_msg.Text      = "Cannot reuse old password";
                            lb_msg.ForeColor = Color.Red;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
        }
示例#11
0
        public static byte[] SHA512(string stringIn)
        {
            SHA512 shaManaged = new SHA512Managed();

            return(shaManaged.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringIn)));
        }
示例#12
0
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            string pwd    = tb_pwd.Text.ToString().Trim();
            string userid = tb_userid.Text.ToString().Trim();

            SHA512Managed hashing = new SHA512Managed();
            string        dbHash  = getDBHash(userid);
            string        dbSalt  = getDBSalt(userid);

            try
            {
                if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                {
                    string pwdWithSalt  = pwd + dbSalt;
                    byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                    string userHash     = Convert.ToBase64String(hashWithSalt);

                    if (userHash.Equals(dbHash))
                    {
                        if (ValidateCaptcha() == true)
                        {
                            if (LockCheck(userid) == "True")
                            {
                                lbl_error.Text      = "Account Locked! Please try again later";
                                lbl_error.ForeColor = System.Drawing.Color.Red;
                            }
                            else
                            {
                                Session["UserID"] = userid;

                                string guid = Guid.NewGuid().ToString();
                                Session["AuthToken"] = guid;
                                Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                                Response.Redirect("Success.aspx", false);
                            }
                        }
                    }
                    else
                    {
                        {
                            if (Session["Lock" + userid] == null)
                            {
                                Session["Lock" + userid] = -2;
                                int tries = (int)Session["Lock" + userid];
                            }

                            else
                            {
                                int tries = (int)Session["Lock" + userid];
                                tries += 1;
                                Session["Lock" + userid] = tries;
                                if (tries > 0)
                                {
                                    SqlConnection connection = new SqlConnection(MYDBConnectionString);
                                    string        sql        = "UPDATE Account SET Lock = 1 WHERE Email=@Email";
                                    SqlCommand    command    = new SqlCommand(sql, connection);
                                    command.Parameters.AddWithValue("@Email", userid);
                                    try
                                    {
                                        connection.Open();
                                        SqlDataReader reader = command.ExecuteReader();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception(ex.ToString());
                                    }
                                    finally { connection.Close(); }
                                }
                            }
                        }
                        lbl_error.Text      = "Email or password is not valid. Please try again.";
                        lbl_error.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }

            finally { }
        }
示例#13
0
        protected void LoginMe(object sender, EventArgs e)
        {
            if (ValidateCaptcha())
            {
                string pwd    = HttpUtility.HtmlEncode(tb_pwd.Text).ToString();
                string userid = HttpUtility.HtmlEncode(tb_email.Text).ToString().Trim();
                if (userid == "" || pwd == "")
                {
                    lblMessage.Text      = "Please enter your credentials.";
                    lblMessage.ForeColor = Color.Red;
                }
                else
                {
                    if (checkValidEmail(userid) == null)
                    {
                        lblMessage.Text      = "You entered Email wrongly.Please try again";
                        lblMessage.ForeColor = Color.Red;
                    }
                    else
                    {
                        var    newdate     = DateTime.Now;
                        string olddate     = forceChangePassword(userid);
                        var    comparedate = DateTime.Parse(olddate);

                        if ((newdate - comparedate).TotalMinutes > 1 && checkAccountLockout(userid) == "True")
                        {
                            ResetAccountLocked(userid);
                        }


                        else
                        {
                            if (checkAccountLockout(userid) == "True")
                            {
                                lblMessage.Text      = "Account is locked out.";
                                lblMessage.ForeColor = Color.Red;
                            }



                            else
                            {
                                Console.WriteLine(olddate);
                                if ((newdate - comparedate).TotalMinutes > 15)
                                {
                                    var statusmsg = "Change your password";
                                    Session["StatusMessage"] = statusmsg;
                                    Response.Redirect("ChangePassword.aspx", false);
                                }

                                //    if (){ }

                                else
                                {
                                    SHA512Managed hashing = new SHA512Managed();
                                    string        dbHash  = getDBHash(userid);
                                    string        dbSalt  = getDBSalt(userid);
                                    try
                                    {
                                        if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                                        {
                                            string pwdWithSalt  = pwd + dbSalt;
                                            byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                            string userHash     = Convert.ToBase64String(hashWithSalt);
                                            if (userHash.Equals(dbHash))
                                            {
                                                Session["UserID"] = userid;

                                                Session["LoggedIn"] = tb_email.Text.Trim();
                                                string guid = Guid.NewGuid().ToString();
                                                Session["AuthToken"] = guid;
                                                Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                                                Response.Redirect("Home.aspx?Email=" + HttpUtility.UrlEncode(userid), false);
                                            }


                                            else
                                            {
                                                if (Session["LogInAttempt" + userid] == null)
                                                {
                                                    Session["LogInAttempt" + userid] = 2;
                                                    int intAttempt = (int)Session["LogInAttempt" + userid];
                                                    lblMessage.Text      = "Email or password is not valid. Please try again. You have " + intAttempt + " left.";
                                                    lblMessage.ForeColor = Color.Red;
                                                }
                                                else
                                                {
                                                    int intAttempt = (int)Session["LogInAttempt" + userid];
                                                    intAttempt -= 1;
                                                    Session["LogInAttempt" + userid] = intAttempt;
                                                    lblMessage.Text      = "Email or password is not valid. Please try again. You have " + intAttempt + " left.";
                                                    lblMessage.ForeColor = Color.Red;
                                                    if (intAttempt < 0)
                                                    {
                                                        SqlConnection connection = new SqlConnection(MYDBConnectionString);
                                                        string        sql        = "UPDATE Account SET accountLockout = 1 WHERE Email=@Email";
                                                        SqlCommand    command    = new SqlCommand(sql, connection);
                                                        command.Parameters.AddWithValue("@Email", userid);
                                                        try
                                                        {
                                                            connection.Open();
                                                            SqlDataReader reader = command.ExecuteReader();
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            throw new Exception(ex.ToString());
                                                        }
                                                        finally { connection.Close(); }
                                                        lblMessage.Text      = "This account has been locked.";
                                                        lblMessage.ForeColor = Color.Red;
                                                    }
                                                    else
                                                    {
                                                        lblMessage.Text      = "Email or password is not valid. Please try again. You have " + intAttempt + " left.";
                                                        lblMessage.ForeColor = Color.Red;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception(ex.ToString());
                                    }
                                    finally { }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#14
0
    protected void ButtonSubmit_Click(object sender, EventArgs e)
    {
        //get from form
        string email      = TextBoxEmail.Text.Trim();
        string password   = TextBoxPassword.Text.Trim();
        string nameMember = TextBoxNameOfMember.Text.Trim();


        //generate salt
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        byte[] saltByte = new byte[8];
        //fills array of bytes
        rng.GetBytes(saltByte);
        salt = Convert.ToBase64String(saltByte);


        //hashing
        SHA512Managed hashing     = new SHA512Managed();
        string        pwdWithSalt = password + salt;

        byte[] hashwithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
        finalHash = Convert.ToBase64String(hashwithSalt);


        //Encryption generation of Random Key and IV
        RijndaelManaged cipher = new RijndaelManaged();

        cipher.GenerateKey();
        Key = cipher.Key;
        IV  = cipher.IV;


        //save to db
        try
        {
            using (SqlConnection con = new SqlConnection(MYDBConnectionString))
            {
                using (SqlCommand cmd =
                           new SqlCommand(
                               "INSERT INTO Account VALUES(@Email,@Name,@PasswordHash,@PasswordSalt,@DateTimeRegistered,@key,@iv,@attempt)")
                       )
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@Email", email);
                        cmd.Parameters.AddWithValue("@Name", encryptData(nameMember));
                        cmd.Parameters.AddWithValue("@PasswordHash", finalHash);
                        cmd.Parameters.AddWithValue("@PasswordSalt", salt);
                        cmd.Parameters.AddWithValue("@DateTimeRegistered", DateTime.Now);
                        cmd.Parameters.AddWithValue("@key", Convert.ToBase64String(Key));
                        cmd.Parameters.AddWithValue("@iv", Convert.ToBase64String(IV));
                        cmd.Parameters.AddWithValue("@attempt", 0);

                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }
    }
示例#15
0
        public byte[] Sha512Hash(byte[] bytes)
        {
            SHA512Managed hash = new SHA512Managed();

            return(hash.ComputeHash(bytes));
        }
示例#16
0
        //
        //
        //
        public byte[] Sha512Hash(Stream stream)
        {
            SHA512Managed hash = new SHA512Managed();

            return(hash.ComputeHash(stream));
        }
示例#17
0
        public static bool VerifyData(byte[] bytesToVerify, string signedMessage, RSAParameters publicKey)
        {
            bool success = false;
            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] signedBytes = Convert.FromBase64String(signedMessage);
                try
                {
                    rsa.ImportParameters(publicKey);

                    SHA512Managed Hash = new SHA512Managed();

                    byte[] hashedData = Hash.ComputeHash(signedBytes);

                    success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return success;
        }
示例#18
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(tbFname.Text))
     {
         lblFnamechecker.ForeColor = Color.Red;
         lblFnamechecker.Text      = "Please fill in your first name!";
         return;
     }
     if (String.IsNullOrEmpty(tbEmail.Text))
     {
         lblEmailchecker.ForeColor = Color.Red;
         lblEmailchecker.Text      = "Please fill in your Email!";
         return;
     }
     if (String.IsNullOrEmpty(tbDob.Text))
     {
         lblDobchecker.ForeColor = Color.Red;
         lblDobchecker.Text      = "Please fill in your birthdate!";
         return;
     }
     if (String.IsNullOrEmpty(tbCreditcard.Text))
     {
         lblCreditchecker.ForeColor = Color.Red;
         lblCreditchecker.Text      = "Please fill in your credit card number!";
         return;
     }
     if (String.IsNullOrEmpty(tbPassword.Text))
     {
         lblPasswordchecker3.ForeColor = Color.Red;
         lblPasswordchecker3.Text      = "Please fill in your password!";
         return;
     }
     if (String.IsNullOrEmpty(tbPasswordconfirm.Text))
     {
         lblPasswordconfirm2.ForeColor = Color.Red;
         lblPasswordconfirm2.Text      = "Please confirm your password!";
         return;
     }
     else
     {
         lblFnamechecker.Text     = "";
         lblEmailchecker.Text     = "";
         lblDobchecker.Text       = "";
         lblCreditchecker.Text    = "";
         lblPasswordchecker3.Text = "";
         lblPasswordconfirm2.Text = "";
         //string pwd = get value from your Textbox
         string pwd = tbPassword.Text.ToString().Trim();;
         //Generate random "salt"
         RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
         byte[] saltByte = new byte[8];
         //Fills array of bytes with a cryptographically strong sequence of random values.
         rng.GetBytes(saltByte);
         salt = Convert.ToBase64String(saltByte);
         SHA512Managed hashing      = new SHA512Managed();
         string        pwdWithSalt  = pwd + salt;
         byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
         byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
         finalHash = Convert.ToBase64String(hashWithSalt);
         RijndaelManaged cipher = new RijndaelManaged();
         cipher.GenerateKey();
         Key = cipher.Key;
         IV  = cipher.IV;
         createAccount();
         Session["LoggedIn"] = tbEmail.Text.Trim();
         Response.Redirect("Home.aspx");
     }
 }
示例#19
0
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            if (!ValidateCaptcha())
            {
                string userEmail = HttpUtility.HtmlEncode(tb_Email.Text.ToString().Trim());
                string pwd       = HttpUtility.HtmlEncode(tb_Password.Text.ToString().Trim());

                SHA512Managed hashing = new SHA512Managed();
                string        dbHash  = getDBHash(userEmail);
                string        dbSalt  = getDBSalt(userEmail);
                string        dbHash2 = getDBHash2(userEmail);
                string        dbSalt2 = getDBSalt2(userEmail);
                string        dbHash3 = getDBHash3(userEmail);
                string        dbSalt3 = getDBSalt3(userEmail);

                string IsVerified = getVerified(userEmail);
                //lb_Error.Text = getDBHash(userEmail);
                try
                {
                    if (IsVerified == "True")
                    {
                        if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                        {
                            if (dbHash2 == null && dbSalt2 == null)
                            {
                                // ************* Start of loggin in ****************
                                string   pwdWithSalt  = pwd + dbSalt;
                                byte[]   hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                string   userHash     = Convert.ToBase64String(hashWithSalt);
                                DateTime datetimenow  = DateTime.Now;
                                //DateTime datetimereset = getResetTime(tb_Email.Text).to;

                                //lb_Error.Text = status + "Test" + status;
                                if (getResetTime(tb_Email.Text) != null)
                                {
                                    DateTime datetimereset = Convert.ToDateTime(getResetTime(tb_Email.Text));
                                    int      comparetime   = DateTime.Compare(datetimenow, datetimereset);
                                    if (comparetime >= 0)
                                    {
                                        accOpen(tb_Email.Text);
                                    }
                                }
                                string status = getStatus(tb_Email.Text);
                                if (status == "Open")
                                {
                                    if (userHash.Equals(dbHash))
                                    {
                                        resetCount(tb_Email.Text);
                                        resetLockoutTimer(tb_Email.Text);
                                        Session["LoggedIn"] = tb_Email.Text.Trim();
                                        //create a new GUID and save into the session
                                        string guid = Guid.NewGuid().ToString();
                                        Session["AuthToken"] = guid;

                                        //Create a new cookie with this guid value
                                        Response.Cookies.Add(new HttpCookie("AuthToken", guid));

                                        Session["UserEmail"] = userEmail;

                                        //insert reset password here if compare(currenttime, maxtime) >= 0
                                        DateTime datetimemax      = Convert.ToDateTime(getMaxPassAge(tb_Email.Text));
                                        DateTime timenow          = DateTime.Now;
                                        int      comparingmaxtime = DateTime.Compare(timenow, datetimemax);
                                        if (comparingmaxtime >= 0)
                                        {
                                            Response.Redirect("PasswordDue.aspx", false);
                                        }
                                        else
                                        {
                                            Response.Redirect("LoggedIn.aspx", false);
                                        }
                                    }
                                    else
                                    {
                                        addCounter(tb_Email.Text);
                                        int counttries = getCounter(tb_Email.Text);
                                        lb_Error.Text = "Email or password is not valid. Please try again. You have " + (3 - counttries) + " tries left.";
                                        //tb_Email.Text = "";
                                        tb_Password.Text = "";
                                        //counttries = counttries + 1;
                                        //Response.Redirect("Login.aspx", false);
                                        if (counttries == 3)
                                        {
                                            accLockout(tb_Email.Text);
                                            lockoutReset(tb_Email.Text);
                                            resetCount(tb_Email.Text);
                                            ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout30()", true);
                                        }
                                    }
                                }
                                else
                                {
                                    ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout()", true);
                                }
                            }
                            else
                            {
                                if (dbHash3 == null && dbSalt3 == null)
                                {
                                    // ************* Start of loggin in ****************
                                    string   pwdWithSalt  = pwd + dbSalt2;
                                    byte[]   hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                    string   userHash     = Convert.ToBase64String(hashWithSalt);
                                    DateTime datetimenow  = DateTime.Now;
                                    //DateTime datetimereset = getResetTime(tb_Email.Text).to;

                                    //lb_Error.Text = status + "Test" + status;
                                    if (getResetTime(tb_Email.Text) != null)
                                    {
                                        DateTime datetimereset = Convert.ToDateTime(getResetTime(tb_Email.Text));
                                        int      comparetime   = DateTime.Compare(datetimenow, datetimereset);
                                        if (comparetime >= 0)
                                        {
                                            accOpen(tb_Email.Text);
                                        }
                                    }
                                    string status = getStatus(tb_Email.Text);
                                    if (status == "Open")
                                    {
                                        if (userHash.Equals(dbHash2))
                                        {
                                            resetCount(tb_Email.Text);
                                            resetLockoutTimer(tb_Email.Text);
                                            Session["LoggedIn"] = tb_Email.Text.Trim();
                                            //create a new GUID and save into the session
                                            string guid = Guid.NewGuid().ToString();
                                            Session["AuthToken"] = guid;

                                            //Create a new cookie with this guid value
                                            Response.Cookies.Add(new HttpCookie("AuthToken", guid));

                                            Session["UserEmail"] = userEmail;
                                            Response.Redirect("LoggedIn.aspx", false);

                                            //insert reset password here if compare(currenttime, maxtime) >= 0
                                            DateTime datetimemax      = Convert.ToDateTime(getMaxPassAge(tb_Email.Text));
                                            DateTime timenow          = DateTime.Now;
                                            int      comparingmaxtime = DateTime.Compare(timenow, datetimemax);
                                            if (comparingmaxtime >= 0)
                                            {
                                                Response.Redirect("PasswordDue.aspx", false);
                                            }
                                            else
                                            {
                                                Response.Redirect("LoggedIn.aspx", false);
                                            }
                                        }
                                        else
                                        {
                                            addCounter(tb_Email.Text);
                                            int counttries = getCounter(tb_Email.Text);
                                            lb_Error.Text = "Email or password is not valid. Please try again. You have " + (3 - counttries) + " tries left.";
                                            //tb_Email.Text = "";
                                            tb_Password.Text = "";
                                            //counttries = counttries + 1;
                                            //Response.Redirect("Login.aspx", false);
                                            if (counttries == 3)
                                            {
                                                accLockout(tb_Email.Text);
                                                lockoutReset(tb_Email.Text);
                                                resetCount(tb_Email.Text);
                                                ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout30()", true);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout()", true);
                                    }
                                }
                                else
                                {
                                    // ************* Start of loggin in ****************
                                    string   pwdWithSalt  = pwd + dbSalt3;
                                    byte[]   hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                    string   userHash     = Convert.ToBase64String(hashWithSalt);
                                    DateTime datetimenow  = DateTime.Now;
                                    //DateTime datetimereset = getResetTime(tb_Email.Text).to;

                                    //lb_Error.Text = status + "Test" + status;
                                    if (getResetTime(tb_Email.Text) != null)
                                    {
                                        DateTime datetimereset = Convert.ToDateTime(getResetTime(tb_Email.Text));
                                        int      comparetime   = DateTime.Compare(datetimenow, datetimereset);
                                        if (comparetime >= 0)
                                        {
                                            accOpen(tb_Email.Text);
                                        }
                                    }
                                    string status = getStatus(tb_Email.Text);
                                    if (status == "Open")
                                    {
                                        if (userHash.Equals(dbHash3))
                                        {
                                            resetCount(tb_Email.Text);
                                            resetLockoutTimer(tb_Email.Text);
                                            Session["LoggedIn"] = tb_Email.Text.Trim();
                                            //create a new GUID and save into the session
                                            string guid = Guid.NewGuid().ToString();
                                            Session["AuthToken"] = guid;

                                            //Create a new cookie with this guid value
                                            Response.Cookies.Add(new HttpCookie("AuthToken", guid));

                                            Session["UserEmail"] = userEmail;
                                            Response.Redirect("LoggedIn.aspx", false);

                                            //insert reset password here if compare(currenttime, maxtime) >= 0
                                            DateTime datetimemax      = Convert.ToDateTime(getMaxPassAge(tb_Email.Text));
                                            DateTime timenow          = DateTime.Now;
                                            int      comparingmaxtime = DateTime.Compare(timenow, datetimemax);
                                            if (comparingmaxtime >= 0)
                                            {
                                                Response.Redirect("PasswordDue.aspx", false);
                                            }
                                            else
                                            {
                                                Response.Redirect("LoggedIn.aspx", false);
                                            }
                                        }
                                        else
                                        {
                                            addCounter(tb_Email.Text);
                                            int counttries = getCounter(tb_Email.Text);
                                            lb_Error.Text = "Email or password is not valid. Please try again. You have " + (3 - counttries) + " tries left.";
                                            //tb_Email.Text = "";
                                            tb_Password.Text = "";
                                            //counttries = counttries + 1;
                                            //Response.Redirect("Login.aspx", false);
                                            if (counttries == 3)
                                            {
                                                accLockout(tb_Email.Text);
                                                lockoutReset(tb_Email.Text);
                                                resetCount(tb_Email.Text);
                                                ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout30()", true);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertLockout()", true);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertVerify()", true);
                    }
                }
                catch (Exception ex)
                {
                    throw new HttpException(400, ex.ToString());
                }
                finally { }
            }
        }
示例#20
0
        protected void REGBTN_Click(object sender, EventArgs e)
        {
            int passnum = 0;

            if (TBFname.Text.ToString() == "" && TBLN.Text.ToString() == "")
            {
                someNum          += 1;
                FNCheck.Text      = "First name cannot be empty";
                LNCheck.Text      = "Last name cannot be empty";
                FNCheck.ForeColor = Color.Red;
                LNCheck.ForeColor = Color.Red;
            }
            else if (TBFname.Text.ToString() == "")
            {
                someNum          += 1;
                FNCheck.Text      = "First name cannot be empty";
                FNCheck.ForeColor = Color.Red;
            }
            else if (TBLN.Text.ToString() == "")
            {
                someNum += 1;

                LNCheck.Text      = "Last name cannot be empty";
                LNCheck.ForeColor = Color.Red;
            }
            if (TBCCN.Text.ToString().Length != 16)
            {
                CreditnoCheck.Text      = "Credit card number must be 16";
                CreditnoCheck.ForeColor = Color.Red;
            }
            if (Regex.IsMatch(TBCCN.Text.ToString(), "[^0-9]"))
            {
                someNum           += 1;
                CreditnoCheck.Text = "Error, characters not accepted. Your text:  " + HttpUtility.HtmlEncode(TBCardName.Text);
            }
            else
            {
                CreditnoCheck.Text = "";
            }
            if (TBEMail.Text.ToString() == "")
            {
                someNum             += 1;
                EmailCheck.Text      = "Credit card number must be 16";
                EmailCheck.ForeColor = Color.Red;
            }
            if (Regex.IsMatch(TBCardName.Text.ToString(), "[^A-Za-z]"))
            {
                someNum += 1;

                CardNameCheck.Text = "Error, characters not accepted. Your text:  " + HttpUtility.HtmlEncode(TBCardName.Text);
            }
            else
            {
                CardNameCheck.Text = "";
            }
            str = TBPW.Text.ToString().Trim();
            if (Regex.IsMatch(str, "[A-Z]"))
            {
                passnum += 1;
            }
            else
            {
                someNum          += 1;
                PWcheck.Text      = "Password must have at least one Uppercase, one Lowercase, one Digit and one Special Character!1";
                PWcheck.ForeColor = Color.Red;
            }
            if (Regex.IsMatch(str, "[a-z]"))
            {
                passnum += 1;
            }
            else
            {
                someNum          += 1;
                PWcheck.Text      = "Password must have at least one Uppercase, one Lowercase, one Digit and one Special Character!2";
                PWcheck.ForeColor = Color.Red;
            }
            if (Regex.IsMatch(str, "[0-9]"))
            {
                passnum += 1;
            }
            else
            {
                someNum          += 1;
                PWcheck.Text      = "Password must have at least one Uppercase, one Lowercase, one Digit and one Special Character!3";
                PWcheck.ForeColor = Color.Red;
            }
            if (Regex.IsMatch(str, "[^a-zA-Z0-9]"))
            {
            }
            else
            {
                someNum          += 1;
                PWcheck.Text      = "Password must have at least one Uppercase, one Lowercase, one Digit and one Special Character!4";
                PWcheck.ForeColor = Color.Red;
            }



            var cvv = TBCVV.Text.ToString();

            if (cvv.Length == 3)
            {
                if (Regex.IsMatch(cvv, "[0-9]"))
                {
                }
                else
                {
                    CVVCheck.Text = "Error, CVV invalid";
                    someNum      += 1;
                }
            }
            else
            {
                CVVCheck.Text = "Error, CVV invalid";
                someNum      += 1;
            }
            CheckEmail(TBEMail.Text.ToString().Trim());
            if (Regex.IsMatch(TBFname.Text.ToString(), "[^A-Za-z0-9]"))
            {
                someNum     += 1;
                FNCheck.Text = "Error, characters not accepted. Your text:  " + HttpUtility.HtmlEncode(TBFname.Text);
            }
            else
            {
                FNCheck.Text = "";
            }
            CheckEmail(TBEMail.Text.ToString().Trim());
            if (Regex.IsMatch(TBLN.Text.ToString(), "[^A-Za-z0-9]"))
            {
                someNum     += 1;
                LNCheck.Text = "Error, characters not accepted. Your text:  " + HttpUtility.HtmlEncode(TBLN.Text);
            }
            else
            {
                LNCheck.Text = "";
            }

            if (someNum == 0)
            {
                PWcheck.Text = "F**K YEAH";
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] saltByte = new byte[8];
                rng.GetBytes(saltByte);
                salt = Convert.ToBase64String(saltByte);

                SHA512Managed hashing = new SHA512Managed();

                string PassWithSalt = str + salt;
                byte[] plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(str));
                byte[] hashwithsalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(PassWithSalt));

                finalHash = Convert.ToBase64String(hashwithsalt);

                RijndaelManaged cipher = new RijndaelManaged();
                cipher.GenerateKey();
                Key = cipher.Key;
                IV  = cipher.IV;

                createAccount();
                Response.Redirect("Login.aspx", false);
            }
        }
示例#21
0
        public static string SHA512Str(byte[] bytesIn)
        {
            SHA512 shaManaged = new SHA512Managed();

            return(BitConverter.ToString(shaManaged.ComputeHash(bytesIn)));
        }
示例#22
0
        internal bool InvokeNetGetData(ref byte msgId, MessageBuffer buffer, ref int index, ref int length)
        {
            if (Main.netMode == 2)
            {
                switch ((PacketTypes)msgId)
                {
                case PacketTypes.ConnectRequest:
                    if (this.InvokeServerConnect(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.ContinueConnecting2:
                    if (this.InvokeServerJoin(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.ChatText:
                    var text = "";
                    using (var stream = new MemoryStream(buffer.readBuffer))
                    {
                        stream.Position = index;
                        using (var reader = new BinaryReader(stream))
                        {
                            reader.ReadByte();
                            reader.ReadRGB();
                            text = reader.ReadString();
                        }
                    }

                    if (this.InvokeServerChat(buffer, buffer.whoAmI, @text))
                    {
                        return(true);
                    }

                    break;

                //Making sure packet length is 38, otherwise it's not a valid UUID packet length.
                //We copy the bytes of the UUID then convert it to string. Then validating the GUID so its the correct format.
                //Then the bytes get hashed, and set as ClientUUID (and gets written in DB for auto-login)
                //length minus 2 = 36, the length of a UUID.
                case PacketTypes.ClientUUID:
                    if (length == 38)
                    {
                        byte[] uuid = new byte[length - 2];
                        Buffer.BlockCopy(buffer.readBuffer, index + 1, uuid, 0, length - 2);
                        Guid guid = new Guid();
                        if (Guid.TryParse(Encoding.Default.GetString(uuid, 0, uuid.Length), out guid))
                        {
                            SHA512 shaM   = new SHA512Managed();
                            var    result = shaM.ComputeHash(uuid);
                            Netplay.Clients[buffer.whoAmI].ClientUUID = result.Aggregate("", (s, b) => s + b.ToString("X2"));
                            return(true);
                        }
                    }
                    Netplay.Clients[buffer.whoAmI].ClientUUID = "";
                    return(true);
                }
            }

            GetDataEventArgs args = new GetDataEventArgs
            {
                MsgID  = (PacketTypes)msgId,
                Msg    = buffer,
                Index  = index,
                Length = length
            };

            this.NetGetData.Invoke(args);

            msgId  = (byte)args.MsgID;
            index  = args.Index;
            length = args.Length;
            return(args.Handled);
        }
示例#23
0
        public string ComputeHash(string plainText, SupportedHash hash)
        {
            int minSaltLength = 4, maxSaltLength = 16;

            Random r          = new Random();
            int    saltLength = r.Next(minSaltLength, maxSaltLength);

            byte[] saltBytes = new byte[saltLength];

            using (var rng = new RNGCryptoServiceProvider())
                rng.GetNonZeroBytes(saltBytes);


            byte[] plainData         = Encoding.UTF8.GetBytes(plainText);
            byte[] plainDataWithSalt = new byte[plainData.Length + saltBytes.Length];

            for (int x = 0; x < plainData.Length; x++)
            {
                plainDataWithSalt[x] = plainData[x];
            }

            for (int n = 0; n < saltBytes.Length; n++)
            {
                plainDataWithSalt[plainData.Length + n] = saltBytes[n];
            }

            byte[] hashValue = null;

            switch (hash)
            {
            case SupportedHash.SHA256:
                SHA256Managed sha = new SHA256Managed();
                hashValue = sha.ComputeHash(plainDataWithSalt);
                sha.Dispose();
                break;

            case SupportedHash.SHA384:
                SHA384Managed sha1 = new SHA384Managed();
                hashValue = sha1.ComputeHash(plainDataWithSalt);
                sha1.Dispose();
                break;

            case SupportedHash.SHA512:
                SHA512Managed sha2 = new SHA512Managed();
                hashValue = sha2.ComputeHash(plainDataWithSalt);
                sha2.Dispose();
                break;
            }

            byte[] result = new byte[hashValue.Length + saltBytes.Length];

            for (int x = 0; x < hashValue.Length; x++)
            {
                result[x] = hashValue[x];
            }

            for (int n = 0; n < saltBytes.Length; n++)
            {
                result[hashValue.Length + n] = saltBytes[n];
            }

            return(Convert.ToBase64String(result));
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SendEmail();



        Double amount = Convert.ToDouble(Label6.Text);

        String text = key.Value.ToString() + "|" + txnid.Value.ToString() + "|" + amount + "|" + "Package" + "|" + TextBox8.Text + "|" + TextBox9.Text + "|" + "1" + "|" + "1" + "|" + "1" + "|" + "1" + "|" + "1" + "||||||" + salt.Value.ToString();

        //Response.Write(text);
        byte[] message = Encoding.UTF8.GetBytes(text);

        UnicodeEncoding UE = new UnicodeEncoding();

        byte[]        hashValue;
        SHA512Managed hashString = new SHA512Managed();
        string        hex        = "";

        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        hash.Value = hex;

        System.Collections.Hashtable data = new System.Collections.Hashtable(); // adding values in gash table for data post
        data.Add("hash", hex.ToString());
        data.Add("txnid", txnid.Value);
        data.Add("key", key.Value);
        // string AmountForm = ;// eliminating trailing zeros

        data.Add("amount", amount);
        data.Add("firstname", TextBox8.Text.Trim());
        data.Add("email", TextBox9.Text.Trim());
        data.Add("phone", TextBox11.Text.Trim());
        data.Add("productinfo", "Package");
        data.Add("udf1", "1");
        data.Add("udf2", "1");
        data.Add("udf3", "1");
        data.Add("udf4", "1");
        data.Add("udf5", "1");

        data.Add("surl", "http://*****:*****@Name", TextBox1.Text);
            //com.Parameters.AddWithValue("@email", TextBox2.Text);
            //com.Parameters.AddWithValue("@address", TextBox3.Text);
            //com.Parameters.AddWithValue("@Package", DataList1.ToString());
            ////com.Parameters.AddWithValue("@PerName", Panel1.ToString());
            ////com.Parameters.AddWithValue("@PerAge", Panel2.ToString());
            ////com.Parameters.AddWithValue("@PerGender", Panel3.ToString());
            //com.Parameters.AddWithValue("@start_date", TextBox7.Text);
            //com.Parameters.AddWithValue("@mode", DropDownList1.SelectedItem.ToString());
            com.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error:" + ex.ToString());
        }
    }
示例#25
0
        public ServerState(
            string dataBasePath,
            int maximumChallengesOutstanding
            )
        {
            this.dataBasePath = dataBasePath;
            this.maximumChallengesOutstanding = maximumChallengesOutstanding;

            crng       = RandomNumberGenerator.Create();
            challenges = new Queue <string>();

            var users_file_path = Path.Combine(dataBasePath, "users.json");

            if (!File.Exists(users_file_path))
            {
                Console.WriteLine($"Creating users.json at location {dataBasePath}.");

                var defusrdata = new Dictionary <string, User>();

                File.WriteAllText(users_file_path, JsonConvert.SerializeObject(defusrdata));
            }

            Console.WriteLine($"Loading users.json from {dataBasePath}.");

            try
            {
                this.users =
                    JsonConvert.DeserializeObject <
                        Dictionary <string, User>
                        >(File.ReadAllText(users_file_path));
            } catch (JsonSerializationException ex)
            {
                Console.WriteLine($"An exception happened during deserialization of the users.json file:\n\n{ex.ToString()}");
                throw;
            }

            string pwhash = "abc";

            {
                var hasher = new SHA512Managed();

                pwhash = BitConverter.ToString(
                    hasher.ComputeHash(Encoding.UTF8.GetBytes(pwhash))
                    ).Replace("-", "").ToLower();
            }

            //foreach (var user in this.users)
            //{
            // Set password for everyone to abc.
            //user.Value.hash = pwhash;
            //}

            // Always ensure at last one user remains. This is the default
            // administrator user.
            if (this.users.Count == 0)
            {
                Console.WriteLine(
                    "Created default admin user because users.json was empty or non-existant."
                    );

                this.users.Add("admin", new User()
                {
                    admin      = true,
                    can_delete = true,
                    hash       = pwhash,
                    name       = "Default Administrator User",
                    user       = "******",
                    userfilter = null,
                });

                this.users.Add("apple", new User()
                {
                    admin      = false,
                    can_delete = false,
                    hash       = pwhash,
                    name       = "Apple User",
                    user       = "******",
                    userfilter = null,
                });

                this.FlushUsersToDisk().Wait();
            }
        }
示例#26
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string pwd = tb_password.Text;
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            byte[] saltByte = new byte[8];
            rng.GetBytes(saltByte);
            salt = Convert.ToBase64String(saltByte);
            SHA512Managed hashing     = new SHA512Managed();
            string        pwdWithSalt = pwd + salt;

            byte[] plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
            byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
            finalHash = Convert.ToBase64String(hashWithSalt);
            RijndaelManaged cipher = new RijndaelManaged();

            cipher.GenerateKey();
            Key = cipher.Key;
            IV  = cipher.IV;
            int    scores = checkPassword(tb_password.Text);
            int    score  = checkinput(tb_firstname.Text, tb_lastname.Text, tb_cci.Text, tb_dob.Text, tb_email.Text);
            string status = "";

            switch (scores)
            {
            case 1:
                status = "Very Weak";
                break;

            case 2:
                status = "Weak";
                break;

            case 3:
                status = "Medium";
                break;

            case 4:
                status = "Strong";
                break;

            case 5:
                status = "Excellent";
                break;
            }
            if (checkemail(tb_email.Text))
            {
                lbl_emailchecker.Text      = "User already exist";
                lbl_emailchecker.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                scores = score + scores;
                if (scores < 4)
                {
                    lbl_pwdchecker.ForeColor = Color.Red;
                    return;
                }
                lbl_pwdchecker.Text = "Status:" + status;

                lbl_pwdchecker.ForeColor = Color.Green;
                createAccount();
                Response.Redirect("Login.aspx");
            }
        }
示例#27
0
        // Login button click event handler
        protected void Login_Click(object sender, EventArgs e)
        {
            string errorMsg    = "";
            string email       = HttpUtility.HtmlEncode(emailAddr.Text.ToString());
            string pwd         = HttpUtility.HtmlEncode(pwdInput.Text.ToString());
            bool   emailExists = EmailCheck(emailAddr.Text.ToString());

            if (ValidateCaptcha())
            {
                if (emailExists)
                {
                    string status = getLockStatus(emailAddr.Text.ToString());
                    if (status == "F")
                    {
                        // Comparing of hash & salts start here
                        SHA512Managed hashing = new SHA512Managed();
                        string        dbHash  = getDBHash(email);
                        string        dbSalt  = getDBSalt(email);
                        try
                        {
                            // If salt and hash exists in database
                            if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                            {
                                string pwdwithSalt  = pwd + dbSalt;
                                byte[] hashwithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdwithSalt));
                                string userhash     = Convert.ToBase64String(hashwithSalt);
                                // Password with Hash matches
                                if (userhash.Equals(dbHash))
                                {
                                    Session["LoggedIn"] = email;
                                    //Create a new GUID and save to session as AuthToken
                                    string guid = Guid.NewGuid().ToString();
                                    Session["AuthToken"] = guid;

                                    //Create a new cookie with this guid value
                                    Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                                    Response.Redirect("Profile.aspx", false);
                                }
                                // else if not locked and have not reached 3 attempts
                                else
                                {
                                    int old_count = GetAttemptCount(email); //2
                                    PlusAttemptCount(email, old_count);     // email, 2 -> counter become 3
                                    int new_count = GetAttemptCount(email); // 3
                                    if (new_count == 3)
                                    {
                                        errorMsg = "Your account has been temporarily locked due to three invalid login attempts.";
                                        SetLockStatus(email);
                                        // Setting Start & End Lock Times
                                        DateTime startLock = DateTime.Now;
                                        DateTime endLock   = startLock.AddMinutes(1);
                                        SetStartTime(email, startLock);
                                        SetEndTime(email, endLock);
                                    }
                                    else
                                    {
                                        errorMsg = $"Email or password is invalid. Attempt Count:{new_count}";
                                    }
                                    errorOrSuccess.Text      = errorMsg;
                                    errorOrSuccess.ForeColor = Color.Red;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.ToString());
                        }
                        finally { }
                    }
                    else if (status == "T")
                    {
                        DateTime endtime = GetEndLockTime(email);
                        TimeSpan diff    = endtime.Subtract(DateTime.Now);
                        if (diff <= TimeSpan.Zero)
                        {
                            SetLockStatusFalse(email);
                            errorOrSuccess.Text      = "Your account is unlocked now";
                            errorOrSuccess.ForeColor = Color.Green;
                        }
                        else
                        {
                            errorOrSuccess.Text      = $"Your account is locked. You have {diff.ToString("%m")} minutes and {diff.ToString("%s")} seconds left before your account is unlocked.";
                            errorOrSuccess.ForeColor = Color.Red;
                        }
                    }
                }
                else
                {
                    errorOrSuccess.Text      = "Your email is not registered.";
                    errorOrSuccess.ForeColor = Color.Red;
                }
            }
            else
            {
                errorOrSuccess.Text      = "There was an error.";
                errorOrSuccess.ForeColor = Color.Red;
            }
        }
示例#28
0
        /// <summary>
        /// Construct a new cryptographically secure random stream object.
        /// </summary>
        /// <param name="a">Algorithm to use.</param>
        /// <param name="pbKey">Initialization key. Must not be <c>null</c> and
        /// must contain at least 1 byte.</param>
        public CryptoRandomStream(CrsAlgorithm a, byte[] pbKey)
        {
            if (pbKey == null)
            {
                Debug.Assert(false); throw new ArgumentNullException("pbKey");
            }

            int cbKey = pbKey.Length;

            if (cbKey <= 0)
            {
                Debug.Assert(false);                 // Need at least one byte
                throw new ArgumentOutOfRangeException("pbKey");
            }

            m_crsAlgorithm = a;

            if (a == CrsAlgorithm.ChaCha20)
            {
                byte[] pbKey32 = new byte[32];
                byte[] pbIV12  = new byte[12];

                using (SHA512Managed h = new SHA512Managed())
                {
                    byte[] pbHash = h.ComputeHash(pbKey);
                    Array.Copy(pbHash, pbKey32, 32);
                    Array.Copy(pbHash, 32, pbIV12, 0, 12);
                    MemUtil.ZeroByteArray(pbHash);
                }

                m_chacha20 = new ChaCha20Cipher(pbKey32, pbIV12, true);
            }
            else if (a == CrsAlgorithm.Salsa20)
            {
                byte[] pbKey32 = CryptoUtil.HashSha256(pbKey);
                byte[] pbIV8   = new byte[8] {
                    0xE8, 0x30, 0x09, 0x4B,
                    0x97, 0x20, 0x5D, 0x2A
                };                                                // Unique constant

                m_salsa20 = new Salsa20Cipher(pbKey32, pbIV8);
            }
            else if (a == CrsAlgorithm.ArcFourVariant)
            {
                // Fill the state linearly
                m_pbState = new byte[256];
                for (int w = 0; w < 256; ++w)
                {
                    m_pbState[w] = (byte)w;
                }

                unchecked
                {
                    byte j = 0, t;
                    int  inxKey = 0;
                    for (int w = 0; w < 256; ++w)                    // Key setup
                    {
                        j += (byte)(m_pbState[w] + pbKey[inxKey]);

                        t            = m_pbState[0];              // Swap entries
                        m_pbState[0] = m_pbState[j];
                        m_pbState[j] = t;

                        ++inxKey;
                        if (inxKey >= cbKey)
                        {
                            inxKey = 0;
                        }
                    }
                }

                GetRandomBytes(512); // Increases security, see cryptanalysis
            }
            else                     // Unknown algorithm
            {
                Debug.Assert(false);
                throw new ArgumentOutOfRangeException("a");
            }
        }
示例#29
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            string email = TB_email.Text.ToString().Trim();

            if (checkemail(email) == null)
            {
                //password protection
                string pwd = TB_pwd.Text.ToString().Trim();
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] saltByte = new byte[8];
                rng.GetBytes(saltByte);
                salt = Convert.ToBase64String(saltByte);
                SHA512Managed hashing      = new SHA512Managed();
                string        pwdWithSalt  = pwd + salt;
                byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
                byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                finalHash = Convert.ToBase64String(hashWithSalt);

                RijndaelManaged cipher = new RijndaelManaged();
                cipher.GenerateKey();
                Key = cipher.Key;
                IV  = cipher.IV;

                //xss = HttpUtility.HtmlEncode(TB_Fname.Text);
                //xss = HttpUtility.HtmlEncode(TB_Lname.Text);
                //xss = HttpUtility.HtmlEncode(TB_email.Text);
                //xss = HttpUtility.HtmlEncode(TB_pwd.Text);

                int    scores = checkPassword(TB_pwd.Text);
                string status = "";
                switch (scores)
                {
                case 1:
                    status = "Very Weak";
                    break;

                case 2:
                    status = "Weak";
                    break;

                case 3:
                    status = "Medium";
                    break;

                case 4:
                    status = "Strong";
                    break;

                case 5:
                    status = "Excellent";
                    break;

                default:
                    break;
                }
                pwd_checker.Text = "Status : " + status;
                if (scores < 4)
                {
                    pwd_checker.ForeColor = Color.Red;
                    return;
                }
                else
                {
                    pwd_checker.ForeColor = Color.Green;

                    createAccount();
                    Response.Redirect("Login.aspx?Comment=" + HttpUtility.UrlEncode(TB_email.Text) + HttpUtility.UrlEncode(TB_pwd.Text)
                                      + HttpUtility.UrlEncode(TB_DoB.Text) + HttpUtility.UrlEncode(TB_Fname.Text) + HttpUtility.UrlEncode(TB_Lname.Text)
                                      + HttpUtility.UrlEncode(TB_cardnum.Text), false);
                }
            }
            else
            {
                lbl_message.ForeColor = Color.Red;
                lbl_message.Text      = "This Email already Exists!";
            }
        }
示例#30
0
        protected void btn_login_Click(object sender, EventArgs e)
        {
            string pass  = tb_login_pass.Text.ToString().Trim();
            string email = tb_login_email.Text.ToString().Trim();

            SHA512Managed hashing     = new SHA512Managed();
            string        dbHash      = getDBHash(email);
            string        dbSalt      = getDBSalt(email);
            int           dbLoginFail = getDBLoginFail(email);

            try
            {
                if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                {
                    if (!(Convert.ToInt32(dbLoginFail) < 3))
                    {
                        lbl_msg.Text = "Account locked";
                    }
                    else
                    {
                        string passWSalt = pass + dbSalt;
                        byte[] hashWSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(passWSalt));
                        string userhash  = Convert.ToBase64String(hashWSalt);

                        if (userhash == dbHash)
                        {
                            Session["loggedIn"] = tb_login_email.Text.ToString().Trim();

                            // reset failed attempts after sucessful log in
                            SqlConnection con    = new SqlConnection(DBconnect);
                            string        sqlstr = "UPDATE [Table] SET Fail_login = 0 WHERE Email=@email";
                            SqlCommand    cmd    = new SqlCommand(sqlstr, con);
                            cmd.Parameters.AddWithValue("@email", email);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();

                            // create a GUID
                            string guid = Guid.NewGuid().ToString();
                            // save new Guid into a session
                            Session["AuthToken"] = guid;

                            // create cookie with save vaule as session "AuthToken"
                            Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                            Response.Redirect("Home.aspx", false);
                        }
                        else
                        {
                            lbl_msg.Text = "Email or Password incorrect. Please try again";
                            addFail(email);
                        }
                    }
                }
                else
                {
                    lbl_msg.Text = "Email or Password incorrect. Please try again 1";
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        // Button - Login
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (validateInput() && ValidateCaptcha())
            {
                string email    = tbEmail.Text.ToString().Trim();
                string password = tbPassword.Text.ToString();

                Account user = Account.RetrieveByEmail(email);

                try
                {
                    if (user != null && password != null)
                    {
                        SHA512Managed hashing      = new SHA512Managed();
                        string        pwdWithSalt  = password + user.PasswordSalt;
                        byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                        string        userHash     = Convert.ToBase64String(hashWithSalt);
                        if (user.LockedFrom != null)
                        {
                            TimeSpan timeRemaining = (TimeSpan)(DateTime.Now - user.LockedFrom);
                            if (timeRemaining.TotalMinutes >= 5)
                            {
                                user.FailedLoginAttempts = 0;
                                user.LockedFrom          = null;
                                Account.Update(user);
                            }
                            else
                            {
                                errorMsg.Text = $"Too many failed login attempts. Try again in {timeRemaining.Subtract(TimeSpan.FromMinutes(5)):mm\\:ss}.";
                                countdown     = (timeRemaining.Subtract(TimeSpan.FromMinutes(5)).TotalSeconds * -1).ToString();
                            }
                        }
                        if (user.LockedFrom == null)
                        {
                            if (userHash.Equals(user.PasswordHash))
                            {
                                user.FailedLoginAttempts = 0;
                                Account.Update(user);

                                TimeSpan passwordAge = DateTime.Now - user.PasswordAge;

                                Session["UserID"] = user.Id;

                                string guid = Guid.NewGuid().ToString();
                                Session["AuthToken"] = guid;
                                Response.Cookies.Add(new HttpCookie("AuthToken", guid));

                                if (passwordAge.TotalMinutes >= 15)
                                {
                                    Session["ChangePassword"] = true;
                                    Response.Redirect("ChangePassword.aspx", false);
                                }
                                else
                                {
                                    Response.Redirect("Profile.aspx", false);
                                }
                            }
                            else
                            {
                                int failedLoginAttempts = 1 + user.FailedLoginAttempts;

                                if (failedLoginAttempts >= 3)
                                {
                                    user.LockedFrom = DateTime.Now;
                                    Account.Update(user);

                                    errorMsg.Text = "Account has been locked due to too many failed login attempts.";
                                }
                                else
                                {
                                    user.FailedLoginAttempts = failedLoginAttempts;
                                    Account.Update(user);

                                    errorMsg.Text = "Email or Password is not valid. Please try again.";
                                }
                            }
                        }
                    }
                    else
                    {
                        errorMsg.Text = "Email or Password is not valid. Please try again.";
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
        }
示例#32
0
 /// <summary>
 /// Hasht einen string mit dem SHA512 Algorithmus
 /// </summary>
 /// <param name="toCrypt">Der zu hashende String</param>
 /// <returns>Den Hashwert des Strings</returns>
 public static string Crypt(string toCrypt)
 {
     using SHA512 theCrypter = new SHA512Managed();
     byte[] hash = theCrypter.ComputeHash(Encoding.UTF8.GetBytes(toCrypt));
     return(BitConverter.ToString(hash).Replace("-", ""));
 }
示例#33
0
 public String makeHash(String RekeningID, String pincode)
 {
     string input = String.Concat(RekeningID,pincode);
     byte[] bytes = Encoding.UTF8.GetBytes(input);
     SHA512Managed hashstring = new SHA512Managed();
     byte[] hash = hashstring.ComputeHash(bytes);
     string hashString = string.Empty;
     foreach (byte x in hash)
     {
         hashString += String.Format("{0:x2}", x);
     }
     return hashString;
 }
示例#34
0
 private static string obf2_(string obf5_)
 {
     using (SHA512 obf3_ = new SHA512Managed())
     {
         byte[] obf4_ = obf3_.ComputeHash(Encoding.UTF8.GetBytes(obf5_));
         StringBuilder obf6_ = new StringBuilder();
         foreach (byte obf7_ in obf4_)
             obf6_.Append(obf7_.ToString("[TIMES2]"));
         return obf6_.ToString();
     }
 }
示例#35
0
        /// <summary>
        /// Create a cryptographic key of length <paramref name="cbOut" />
        /// (in bytes) from <paramref name="pbIn" />.
        /// </summary>
        public static byte[] ResizeKey(byte[] pbIn, int iInOffset,
                                       int cbIn, int cbOut)
        {
            if (pbIn == null)
            {
                throw new ArgumentNullException("pbIn");
            }
            if (cbOut < 0)
            {
                throw new ArgumentOutOfRangeException("cbOut");
            }

            if (cbOut == 0)
            {
                return(MemUtil.EmptyByteArray);
            }

            byte[] pbHash;
            if (cbOut <= 32)
            {
                pbHash = HashSha256(pbIn, iInOffset, cbIn);
            }
            else
            {
                using (SHA512Managed h = new SHA512Managed())
                {
                    pbHash = h.ComputeHash(pbIn, iInOffset, cbIn);
                }
            }

            if (cbOut == pbHash.Length)
            {
                return(pbHash);
            }

            byte[] pbRet = new byte[cbOut];
            if (cbOut < pbHash.Length)
            {
                Array.Copy(pbHash, pbRet, cbOut);
            }
            else
            {
                int   iPos = 0;
                ulong r    = 0;
                while (iPos < cbOut)
                {
                    Debug.Assert(pbHash.Length == 64);
                    using (HMACSHA256 h = new HMACSHA256(pbHash))
                    {
                        byte[] pbR    = MemUtil.UInt64ToBytes(r);
                        byte[] pbPart = h.ComputeHash(pbR);

                        int cbCopy = Math.Min(cbOut - iPos, pbPart.Length);
                        Debug.Assert(cbCopy > 0);

                        Array.Copy(pbPart, 0, pbRet, iPos, cbCopy);
                        iPos += cbCopy;
                        ++r;

                        MemUtil.ZeroByteArray(pbPart);
                    }
                }
                Debug.Assert(iPos == cbOut);
            }

#if DEBUG
            byte[] pbZero = new byte[pbHash.Length];
            Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero));
#endif
            MemUtil.ZeroByteArray(pbHash);
            return(pbRet);
        }
示例#36
0
        protected void btnPwdChg_Click(object sender, EventArgs e)
        {
            string        pwd          = tb_currentPwd.Text.ToString().Trim();
            string        userid       = tb_email.Text.ToString().Trim();
            string        newPwd       = tb_newPwd.Text.ToString().Trim();
            SHA512Managed hashingCheck = new SHA512Managed();
            string        dbHash       = getDBHash(userid);
            string        dbSalt       = getDBSalt(userid);

            try
            {
                if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                {
                    string pwdWithSaltCheck  = pwd + dbSalt;
                    byte[] hashWithSaltCheck = hashingCheck.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSaltCheck));
                    string userHash          = Convert.ToBase64String(hashWithSaltCheck);

                    if (String.IsNullOrEmpty(getTimeOfPwdChange(userid)) == true)
                    {
                        if (userHash.Equals(dbHash))
                        {
                            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                            byte[] saltByte = new byte[8];

                            rng.GetBytes(saltByte);
                            salt = Convert.ToBase64String(saltByte);
                            SHA512Managed hashing      = new SHA512Managed();
                            string        pwdWithSalt  = newPwd + salt;
                            byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(newPwd));
                            byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                            finalHash = Convert.ToBase64String(hashWithSalt);
                            RijndaelManaged cipher = new RijndaelManaged();
                            cipher.GenerateKey();
                            Key = cipher.Key;
                            IV  = cipher.IV;

                            int noCheck = checkPassword(tb_newPwd.Text.ToString());

                            if (noCheck < 5)
                            {
                                errorMsg.Text      = "Password is too weak. Please use a different password";
                                errorMsg.ForeColor = Color.Red;
                            }
                            else
                            {
                                updatePassword(userid, finalHash, salt);
                                updateTimeOfPwdChange(userid, DateTime.Now.ToString());
                                errorMsg.Text = "";
                                Response.Redirect("HomePage.aspx");
                            }
                        }
                        else
                        {
                            errorMsg.ForeColor = Color.Red;
                            errorMsg.Text      = "Current password entered is wrong. Please try again.";
                            tb_currentPwd.Text = "";
                            tb_email.Text      = "";
                            tb_newPwd.Text     = "";
                        }
                    }
                    else
                    {
                        var checkTime = (DateTime.Now - Convert.ToDateTime(getTimeOfPwdChange(userid))).TotalMinutes;

                        if (checkTime >= 5)
                        {
                            if (userHash.Equals(dbHash))
                            {
                                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                byte[] saltByte = new byte[8];

                                rng.GetBytes(saltByte);
                                salt = Convert.ToBase64String(saltByte);
                                SHA512Managed hashing      = new SHA512Managed();
                                string        pwdWithSalt  = newPwd + salt;
                                byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(newPwd));
                                byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                finalHash = Convert.ToBase64String(hashWithSalt);
                                RijndaelManaged cipher = new RijndaelManaged();
                                cipher.GenerateKey();
                                Key = cipher.Key;
                                IV  = cipher.IV;

                                int noCheck = checkPassword(tb_newPwd.Text.ToString());

                                if (noCheck < 5)
                                {
                                    errorMsg.Text      = "Password is too weak. Please use a different password";
                                    errorMsg.ForeColor = Color.Red;
                                }
                                else
                                {
                                    updatePassword(userid, finalHash, salt);
                                    updateTimeOfPwdChange(userid, DateTime.Now.ToString());
                                    errorMsg.ForeColor = Color.Green;
                                    errorMsg.Text      = "Password has been updated!";
                                    Response.Redirect("HomePage.aspx", false);
                                }
                            }
                            else
                            {
                                errorMsg.ForeColor = Color.Red;
                                errorMsg.Text      = "Current password entered is wrong. Please try again.";
                                tb_currentPwd.Text = "";
                                tb_email.Text      = "";
                                tb_newPwd.Text     = "";
                            }
                        }
                        else
                        {
                            errorMsg.ForeColor = Color.Red;
                            errorMsg.Text      = "Cannot change password too quickly! Please wait 5 minutes";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally { }
        }
示例#37
0
        /// <summary>
        /// Computes the SHA512 hash from a password string
        /// </summary>
        /// <param name="password">The password string.</param>
        /// <returns>The binary hash.</returns>
        internal static byte[] ComputePasswordHash(string password)
        {
            HashAlgorithm hashalg = new SHA512Managed();

            return(hashalg.ComputeHash(Encoding.Unicode.GetBytes(password)));
        }
示例#38
0
     public static string GetSHA512(string text)
     {
         ASCIIEncoding UE = new ASCIIEncoding();
         byte[] hashValue;
         byte[] message = UE.GetBytes(text);

         SHA512Managed hashString = new SHA512Managed();
         string hex = "";

         hashValue = hashString.ComputeHash(message);
         foreach (byte x in hashValue)
         {
             hex += String.Format("{0:x2}", x);
         }
         return hex;
     }