How To Encrypt A Password

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.

  1. Use CRYPT_GEN_RANDOM function for PasswordSalt,
    1. DECLARE @pswd NVARCHAR(MAX) = 'Kuldeep Patel'  
    2. DECLARE @salt VARBINARY(4) = CRYPT_GEN_RANDOM(4)  
    3. DECLARE @hash VARBINARY(MAX)  
    4. SET @hash = 0x0100 + @salt + HASHBYTES('SHA1', CAST(@pswd AS VARBINARY(MAX)) + @salt)  
    5. SELECT @salt AS PasswordSalt, @hash AS PasswordHashValue, PWDCOMPARE(@pswd, @hash) AS IsPasswordHash  
  2. Use NEWID() function for PasswordSalt,
    1. DECLARE @pswd NVARCHAR(MAX) = 'Kuldeep Patel'  
    2. DECLARE @salt VARBINARY(4);  
    3. SET @salt = CAST(NEWID() AS VARBINARY(4))  
    4. DECLARE @hash VARBINARY(MAX)  
    5. SET @hash = 0x0100 + @salt + HASHBYTES('SHA1', CAST(@pswd AS VARBINARY(MAX)) + @salt)  
    6. SELECT @salt AS PasswordSalt, @hash AS PasswordHashValue, PWDCOMPARE(@pswd, @hash) AS IsPasswordHash