2015-10-01 9 views
7

nel mio database SQL ho,Hash è diverso in SQL e C#?

DECLARE @InputString nvarchar(15) ='pass' 
DECLARE @InputSalt nvarchar(36) = 'FC94C37C-03A3-49A3-9B9F-D4A82E708618' 

DECLARE @HashThis nvarchar(100) 
Declare @BinaryHash varbinary(max) 
set @HashThis = @InputString + @InputSalt 
set @BinaryHash= HASHBYTES('SHA1', @HashThis) 
SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:variable("@BinaryHash")))', 'VARCHAR(MAX)') 

e C# che ho,

public static string HashString(string cleartext) 
{ 
    byte[] clearBytes = System.Text.Encoding.UTF8.GetBytes(cleartext); 
    return HashBytes(clearBytes); 
} 

public static string HashBytes(byte[] clearBytes) 
{ 
    var hasher = System.Security.Cryptography.SHA1.Create(); 
    byte[] hashBytes = hasher.ComputeHash(clearBytes); 
    string hash = System.Convert.ToBase64String(hashBytes); 
    hasher.Clear(); 
    return hash; 
} 
HashString("passFC94C37C-03A3-49A3-9B9F-D4A82E708618") 

Ma l'hash è diverso?

C# Output: S55Nz1lyGweoJEHWcC6zFxJDKWQ= 
SQL Output: 4jqyC1pLJ0hW+AMNk8GOWCC99KY= 

https://dotnetfiddle.net/4bwAtm

+0

Qual è l'output di entrambi? – CodeCaster

+0

@CodeCaster, post upated – user960567

+0

Il valore C# (S55Nz1lyGweoJEHWcCzzzxx6DJQQ =) sembra essere quello corretto per l'input, è necessario correggere il codice SQL. –

risposta

6

La vostra funzione di hash viene eseguito su byte, non su caratteri. Si traducono efficacemente i caratteri in byte, ma non lo si fa nello stesso modo in C# come in SQL: si usa nvarchar (UTF-16) da SQL, si usa UTF-8 da C#. Puoi cambiare o per abbinare l'altro.

Dato che non si dispone di caratteri non ASCII nel test corrente, per quella particolare password, è possibile verificare facilmente che questo è il problema semplicemente cambiando nvarchar in varchar nel proprio SQL. Tuttavia, ciò non sarà sufficiente per l'intera gamma di caratteri Unicode.

+0

OK Grazie Come posso aggiornare il codice C#. Non riesco ad aggiornare SQL perché il nostro sistema esistente si basa su questo. – user960567

+0

Ho cambiato UTF-8 in UTF-16, 'System.Text.Encoding.Unicode.GetBytes (cleartext);' e il suo funzionamento. Questa è una correzione corretta? – user960567

+0

Non funziona quando abbiamo caratteri arabi. Per favore aiutami a risolvere questo problema. posso solo cambiare C# – user960567

Problemi correlati