c# - Validate Stored Encrypted Password in SQL Server 2012 -
in sql server run command:
select hashbytes('sha2_256', '12345678') encryptedstring
it gives 0xef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f
string output, string has 66 characters.
on same side, itried encrypt password c# code, using this:
public string getshaencryptedcode(string text) { //sha1 sha26 = new sha1cryptoserviceprovider(); sha256 sha26 = new sha256cryptoserviceprovider(); byte[] sha256bytes = system.text.encoding.utf8.getbytes(text); byte[] crystring = sha26.computehash(sha256bytes); string sha256str = string.empty; (int = 0; < crystring.length; i++) { sha256str += crystring[i].tostring("x"); } return sha256str; }
suupose, if enter same "12345678" in c# code returns me string of 62 character long, string ef797c8118f02dfb64967dd5d3f8c762348c9c63d532cc95c5ed7a898a64f
. how validate encrypted string coming sql server , other string c# code in order login user login page?
your c# format string incorrect - it missing leading 0
s when hex value less 10
.
instead need use "x2"
format string padded 2 numbers:
public string getshaencryptedcode(string text) { //sha1 sha26 = new sha1cryptoserviceprovider(); sha256 sha26 = new sha256cryptoserviceprovider(); byte[] sha256bytes = system.text.encoding.utf8.getbytes(text); byte[] crystring = sha26.computehash(sha256bytes); string sha256str = string.empty; (int = 0; < crystring.length; i++) { sha256str += crystring[i].tostring("x2"); } return sha256str; }
this correctly returns ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f
, can append 0x
start.
in case, should not converting values string anyway. hashbytes()
, sha256.computehash()
both return byte arrays, more efficient , safer compare instead. can use methods described in this answer that.
or maybe better still, assume storing password in database encrypted (aren't you...?), encrypt input value byte array in c#, pass database , use like
select * users username = @username , password = @passwordbytes
Comments
Post a Comment