Hashing password with Salt
Generate hash in Sql
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
- Guid is SQL is in UPPER Case while .Net Guid is in lower case
- 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
- update dbo.Tenant set TenantPasscodeSalt=NEWID();
- 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;