I'm trying to generate an md5 hash and store it as a hex string via C# program (not related to passwords!), but I need to replicate an existing node method. When I check my generated hashes against ones generated by node they do not match. I suspect it has something to do with encoding, but I've tried both UTF8 and ASCII and am not getting much luck. Any help appreciated.
The node method is below:
public static hash(...data: string[]): string {
var md5sum = createHash('md5');
md5sum.update(data?.join() ?? '');
var hash = md5sum.digest('hex');
return hash;
}
C# method
public static string CalculateHash(string[] inputs)
{
var hashInput = String.Join("", inputs);
using (var md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(hashInput);
byte[] hashBytes = md5.ComputeHash(inputBytes);
var sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i )
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
CodePudding user response:
JavaScripts data?.join()
joins strings with a comma, i.e. ["Hello", "World"].join()
yields "Hello,World"
.
In C#, you explicitly join the strings without separator, so String.Join("", new[] {"Hello", "World"})
yields "HelloWorld"
.
If you change your C# code line to
var hashInput = String.Join(",", inputs);
both methods yield the same result (C# fiddle, JavaScript fiddle).
CodePudding user response:
I don't quite understand your question but maybe that's what you mean
static void Main()
{
Console.WriteLine(GetHashMD5("Hello World"));
Console.WriteLine(GetHashMD5("Hello World"));
}
public static string GetHashMD5(string value)
{
using (MD5 md5 = MD5.Create())
{
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
var hashed = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
// x = Lowercase | X = Uppercase
hashed.Append(b.ToString("x4"));
}
return hashed.ToString();
}
}
Output:
00b1000a008d00b1006400e000750041000500b700a9009b00e7002e003f00e5 00b1000a008d00b1006400e000750041000500b700a9009b00e7002e003f00e5