Encrypt passwords on Sql Server 2008 using SHA1

前端 未结 1 778
眼角桃花
眼角桃花 2021-01-23 04:39

I have designed a Log In System using C# where the username and password is checked in SQL server 2008 before loading the main page. I wish to encrypt the stored password on the

相关标签:
1条回答
  • 2021-01-23 05:20

    Hash and salt passwords in C#

    https://crackstation.net/hashing-security.htm

    https://www.bentasker.co.uk/blog/security/201-why-you-should-be-asking-how-your-passwords-are-stored

    As I stated in my comments, hashing passwords is something that you probably shouldn't be doing yourself.

    A few things to note:

    • SHA1 is not recommended for passwords
    • Passwords should be salted
    • You should use a verified userstore framework rather than attempting to create your own, as you will likely "do it wrong"
    • I'm sure there are many more

    That being said, to accomplish your specific question, you would want something like this:

    Users
    ----
    userId
    passwordHashed
    

    passwordHashed stores a hashed version of the user's password (the plain text password is never stored anywhere in persistence.)

    for checking for valid password something like this is done:

    ALTER procedure [dbo].[proc_UserLogin]
     @userid varchar(20),
      @password nvarchar(50)
      As 
    
      declare
      @ReturnVal              varchar(500)
    
    
    SET NOCOUNT ON      
    
      if exists(select userid,password from LoginManager where userid=@userid and password=HASHBYTES('SHA1', @password))
      set @ReturnVal='0|Logged in Successfully'
      else
      set @ReturnVal='1|Login Failed/Username does not exist'
    
      select @ReturnVal
    

    For inserting/updating user passwords, you need to make sure to store the hashed password not the plain text password, as such;

    INSERT INTO users(userId, passwordHashed) 
    VALUES (@userId, HASHBYTES('SHA1', @rawPassword)
    

    or

    UPDATE users 
    SET passwordHased = HASHBYTES('SHA1', @rawPassword) 
    WHERE userId = @userId
    

    EDIT:

    just realized you're asking how to accomplish the hash in C#, not SQL. You could perform the following (taken from Hashing with SHA1 Algorithm in C#):

    public string Hash(byte [] temp)
    {
        using (SHA1Managed sha1 = new SHA1Managed())
        {
            var hash = sha1.ComputeHash(temp);
            return Convert.ToBase64String(hash);
        }
    }
    

    Your code snip could be:

                conn.Open();
                string query = "EXEC dbo.proc_UserLogin'" + username.Text+ "', '" + this.Hash(System.Text.Encoding.UTF8.GetBytes(password.Text))+"'";
                OleDbCommand cmd = new OleDbCommand(query, conn);
    

    You should also note that you should parameterize your parameters to your stored procedure rather than passing them in the manner you are - which it looks like you already have a separate question in regarding that.

    0 讨论(0)
提交回复
热议问题