Reputation: 36311
I am trying to calculate a sha256
, and this code seems to be doing it wrong.
private static string GetSHA256(string text){
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue){
hex += string.Format("{0:x2}", x);
}
return hex;
}
I have a server that generates a sha256
based on data sent to it, and the the value from this sha256
doesn't match the one on the server. I have tried generating the same using PHP
, and JavaScript
, and those both generate the same sha256
as the server, so I have come to the conclusion that this has to be what is wrong.
with php I am using this:
$time = time();
$str = "5550d868c5242fb3299a2604|$time|1431619392-36e2d4f3b5de0bfd5f26e3efabbbd99dc2503dab";
$hash = hash("sha256", $str);
Here is what is getting hashed with C#
string time = ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();
GetSHA256("5550d868c5242fb3299a2604|"+time+"|1431619392-36e2d4f3b5de0bfd5f26e3efabbbd99dc2503dab")
As you can see they are both the same format, so I think that this is the issue. Can anyone see how I am hashing differently in C#?
Upvotes: 1
Views: 1700
Reputation: 56536
UnicodeEncoding
uses UTF-16 encoding. Your encoding should match what PHP uses, which is probably either UTF-8 or ASCII (which are equivalent if you only use the common, simple characters used in your example).
private static string GetSHA256(string text){
byte[] message = Encoding.UTF8.GetBytes(text);
SHA256Managed hashString = new SHA256Managed();
byte[] hashValue = hashString.ComputeHash(message);
string hex = "";
foreach (var x in hashValue){
hex += string.Format("{0:x2}", x);
}
return hex;
}
Upvotes: 4