T-SQL: Salted Passwords

2020-03-02 04:35发布

问题:

I am looking for an example of salting passwords withing a T-SQL Stored Procedure. And of course the matching proc to validate a user.

CREATE PROC ChangePassword(@Username nVarChar(50), @Password nVarChar(50))

CREATE PROC ValidateUser(@Username nVarChar(50), @Password nVarChar(50))

回答1:

First, I'm going to go out on a limb here and say that hashing passwords in the database is in general a bad practice with respect to security. You would not be protected against traffic sniffers watching traffic to the database. The only way to protect against that is to ensure your connection to the database was encrypted which generally means all other traffic to the database is going to be encrypted. It's possible to work around this, but the better solution is to have the application(s) do the hashing.

As Sam Saffron stated, you can use the Hashbytes functions to get SHA1 hashing. If you want better algorithms you would need to create a CLR procedure. Salting would involve storing a cryptographically random value for each user, then appending that value to the password and running it through Hashbytes:

Create Procedure ValidateUser
    @Username nvarchar(50)
    , @Password nvarchar(50)
As

Declare @PasswordSalt varbinary(256)

Set @PasswordSalt = ( Select PasswordSalt From Users Where Username = @Username )

If @PasswordSalt Is Null
        -- generate a salt? 

Declare @Hash varbinary(max)
Set @Hash = Hashbytes('SHA1', @PasswordSalt + Cast('|' As binary(1)) + Cast(@Password As varbinary(100))

If Exists(  Select 1
            From Users
            Where Username = @Username
                And PasswordHash = @Hash )
    -- user is valid

Else
    -- user is not valid

Remember that the salt should be cryptographically random so I would not recommend using NewId(). Instead, I would generate that using something like .NET's RNGCryptoServiceProvider class.



回答2:

You can use HASHBYTES to SHA1 a string, and NEWID() to generate a random Guid as salt.



回答3:

have you considered salting passswords at the application level as.the server hardware for app servers esp. Cpu might have been more suitable than the dbms's to process hashing and salting?