Labels

CSOM (1) JavaScript (1) SharePoint (1)

Thursday, August 24, 2017

Hashing password with Salt

Hashing password with Salt

Generate hash in Sql
SELECT HASHBYTES('SHA2_512', 'password-plaintext');

Generate hash in .Net
SHA512 hash = SHA512Managed.Create();
saltedPassword=password+Guid.NewGuid().ToString().ToUpper();
byte[] passwordHash = hash.ComputeHash(Encoding.UTF8.GetBytes(saltedPassword));

salt used is Guid

Points to Note to match HASH generated in SQL  and .Net 
  1. Guid is SQL is in UPPER Case while .Net Guid is in lower case
  2. string equivalent in .Net is varchar and NOT nvarchar, so use CAST(N'xxxxxx' as varchar(50)) in case its variable is of type nvarchar





can use below script to generate salt and hash
 
  1. update dbo.Tenant set TenantPasscodeSalt=NEWID();
  2. update dbo.Tenant set TenantPasscodeHash= HASHBYTES( 'SHA2_512',CAST(TenantPasscode as VARCHAR(50))+CAST(TenantPasscodeSalt as VARCHAR(50)))

byte[] passwordHash;
salt =Guid.NewGuid();
            using (SHA512 hash = SHA512Managed.Create())
            {
                string saltedPassword = password + salt.ToString().ToUpper();
                passwordHash = hash.ComputeHash(Encoding.UTF8.GetBytes(saltedPassword));
            }

SqlParameter paramTenantPasscodeHash = cmd.Parameters.Add("@TenantPasscodeHash", SqlDbType.VarBinary, 128);
                        paramTenantPasscodeHash.Value = passwordHash;