locked
C# hash Encoded value not matching with SQL HashBytes function value RRS feed

  • Question

  • User-1410221107 posted

    I have created hash value using below function in sql

    SQL Query

    Select hashbytes('MD5', PNumber+CONVERT(VARCHAR(50),cast(datestamp as binary),1)) From dbo.Events

    Now i need to get the equivalent C# function in order to get the hash value and pass it to Store Proc.

    I am using below code to get the c# equivalent. But values are not matching

    C# Code

    var strDate = policyEventFromQueue.DateStamp.ToString();
    var binaryvalue = Encoding.Unicode.GetBytes(strDate);
    var hashkey = GetMD5Hash(PNumber + binaryvalue);
    
    public static byte[] GetMD5Hash(string input)
    {
    System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] bs = System.Text.Encoding.Unicode.GetBytes(input);
    
    bs = x.ComputeHash(bs);
    return bs;
    }

    Here are test result:

    From SQL

    PNumber ='4272535529'
    DateStamp ='2016-06-30 12:19:35.257961'
    
    HashValue : 0x104E09499B76CB59420AEEEDBBE187F8
    
    DateStamp is DateTime2 Field

    In C# I am getting the value from DB Field value as below

    [0]: 16
    [1]: 78
    [2]: 9
    [3]: 73
    [4]: 155
    [5]: 118
    [6]: 203
    [7]: 89
    [8]: 66
    [9]: 10
    [10]: 238
    [11]: 237
    [12]: 187
    [13]: 225
    [14]: 135
    [15]: 248

    From C# GetMD5Hash Function i am getting value as below

    [0]: 30
    [1]: 153
    [2]: 105
    [3]: 203
    [4]: 34
    [5]: 124
    [6]: 20
    [7]: 12
    [8]: 207
    [9]: 113
    [10]: 210
    [11]: 144
    [12]: 18
    [13]: 145
    [14]: 22
    [15]: 36
    
    

    Any suggestion will be appreciated.

    Wednesday, August 3, 2016 3:23 PM

Answers

  • User753101303 posted

    Hi,

    IMO could be that you are using Unicode on the C# side but VARCHAR on the SQL side. What if using NVARCHAR(50) instead (and check and change PNumber if needed).

    Edit: also I would start for example with SELECT hashbytes('md5',N'AB') and would encrypt AB on the C# side. It seems you include an hexa string (including its 0x prefix) on the SQL Side but I'm not sure if you handle this string the same way on the C# side. So try maybe first with an hardcoded simple string before adding this kind of feature to make sure where it start to fails and make sure the actual hashed value on both sides is REALLY the same (possibly showing the value just before encryption in debug mode).

    Edit2 : ah and moreover you are using binary rather than varbinary so I really doubt ypu really end up with encrypting the same string on both sides. Do a SELECT to just keep the exact string you are about to hash and make sure the final string you are trying to hash on the C# side is really the same even before hashing it.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 3, 2016 3:55 PM