sqlsql-serverhashpasswords

How to insert a hashed password to a table?


I want to store hashed password in my database.
How can use the HASHBYTES method to store hashed password in Users table ?

CREATE TABLE [Users](
    EmailAddress NVARCHAR(320) UNIQUE,
    UserID INT IDENTITY(1,1) PRIMARY KEY,
    UserPassword NVARCHAR(32), -- I Edited the length
    FirstName VARCHAR(256) not null,
    LastName VARCHAR(256) not null,
    MobileNumber BIGINT,
)

--I checked and found this is how to hash a password

declare @afterhash varbinary(256) = HASHBYTES('SHA2_256', 'P@ssw0rd')

But how do I combine them both?


Solution

  • As mentioned, I don't understand the problem here. Just use HASHBYTES in your parametrised INSERT:

    INSERT INTO dbo.Users (EmailAddress, UserPassword, FirstName, LastName, MobileNumber)
    VALUES(@EmailAddress, HASHBYTES('SHA2_256',@Password), @FirstName, @LastName, @MobileNumber); 
    

    Side Note: As I mentioned in my other answer, bigint isn't the right choice for a telephone number. Phone Numbers can start with a 0 and contain other characters from digits. A value like '01234567890' would be changed to 1234567890, a number like '+441234567890' would be changed to 441234567890, and a number like '(01234) 567890' would fail to INSERT completely