简体   繁体   中英

Hash string with SHA256 key

I can't get the correct HASH and I really have no idea what is wrong with it. All hashes I get aren't correct as on this site: http://hash.online-convert.com/sha256-generator

public NavigatedPage ()
{
    string bytes = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Command>  <LMI_PAYMENT_NO>1000</LMI_PAYMENT_NO><LMI_MERCHANT_ID>2096</LMI_MERCHANT_ID>  <LMI_HASH></LMI_HASH>  <LMI_PAYMENT_SYSTEM>18</LMI_PAYMENT_SYSTEM>  <LMI_PAYMENT_AMOUNT>1001</LMI_PAYMENT_AMOUNT>  <LMI_PAYMENT_DESC>Оплата договора</LMI_PAYMENT_DESC></Command>";
    string key = "14653285";
    string message = bytes;//xml document in a string
    
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    
    byte[] keyByte = encoding.GetBytes(key);
    
    HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
    
    byte[] messageBytes = encoding.GetBytes(message);
    
    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
    
    var tempHash = ByteToString(hashmessage);
}

public static string ByteToString(byte[] buff)
{
    string sbinary = "";

    for ( int i = 0; i < buff.Length; i++ )
    {
        sbinary += buff[ i ].ToString("X2"); // hex format
    }
    return ( sbinary );
}

That's what i've done, but it gives me wrong result.

When you put your string into the Text you want to convert to a SHA-256 hash: textbox on the site you linked, you have to remove the c# escape characters for your string (in this case replace \\" with " ) then you get the same result - your code works.

This is because C# will see \\" as an escaped " and the site will not (therefore including it in the hash)

Your Result

Their Result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM