Problem
The passwords are usually stored in the database. Plain text password is very vulnerable, because if an attacker accesses the database, he/she can steal the users' passwords.
Solutions
An encrypted password is very secure, because if an attacker accesses the database, he/she can't steal the users' passwords.
SHA1 is a cryptographic hash function. Its result is usually expressed as a 160 bit hex number.
PWDCOMPARE function is used to compare the plain text password and the encrypted password. if the plain text password and the encrypted password does not match, then this function returns 1, else return 0.
- Use CRYPT_GEN_RANDOM function for PasswordSalt,
- DECLARE @pswd NVARCHAR(MAX) = 'Kuldeep Patel'
- DECLARE @salt VARBINARY(4) = CRYPT_GEN_RANDOM(4)
- DECLARE @hash VARBINARY(MAX)
- SET @hash = 0x0100 + @salt + HASHBYTES('SHA1', CAST(@pswd AS VARBINARY(MAX)) + @salt)
- SELECT @salt AS PasswordSalt, @hash AS PasswordHashValue, PWDCOMPARE(@pswd, @hash) AS IsPasswordHash
- Use NEWID() function for PasswordSalt,
- DECLARE @pswd NVARCHAR(MAX) = 'Kuldeep Patel'
- DECLARE @salt VARBINARY(4);
- SET @salt = CAST(NEWID() AS VARBINARY(4))
- DECLARE @hash VARBINARY(MAX)
- SET @hash = 0x0100 + @salt + HASHBYTES('SHA1', CAST(@pswd AS VARBINARY(MAX)) + @salt)
- SELECT @salt AS PasswordSalt, @hash AS PasswordHashValue, PWDCOMPARE(@pswd, @hash) AS IsPasswordHash