I am trying to achieve the computed hash in C# which should match the hash generated by the Perl's module
The perl code is below
#!/user/bin/perl
#
use Digest::MD5 'md5_hex';
my $rawvalue = "HelloWorld";
my $salt = "12345678";
my $md5 = Digest::MD5->new;
$md5->add($rawvalue,$salt);
my $md5Digest = $md5->hexdigest;
print $md5Digest;
print "\n";
The output is : a4584f550a133a7f47cc9bafd84c9870
I've tried the following approaches in C# - but am not able to achieve the same result.
string salt = "12345678";
string data = "HelloWorld";
byte[] saltbyte = System.Text.Encoding.UTF8.GetBytes(salt);
byte[] databyte = System.Text.Encoding.UTF8.GetBytes(data);
//HMACMD5
HMACMD5 hmacmd5 = new HMACMD5(saltbyte);
byte[] hmacmd5hash = hmacmd5.ComputeHash(databyte);
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < hmacmd5hash.Length; i++)
{
sBuilder.Append(hmacmd5hash[i].ToString("x2"));
}
Console.WriteLine(sBuilder.ToString()); //outputs 2035a1ff1bf3a5ddec8445ada2e4883c
//HMACSHA1
HMACSHA1 hmacsha1 = new HMACSHA1(saltbyte);
byte[] hmacsha1hash = hmacsha1.ComputeHash(databyte);
sBuilder = new StringBuilder();
for (int i = 0; i < hmacsha1hash.Length; i++)
{
sBuilder.Append(hmacsha1hash[i].ToString("x2"));
}
Console.WriteLine(sBuilder.ToString()); //outputs a8beb5b2f63c9574fea28f4c1d9e59306a007924
As a last resort I may resort to enabling perl cgi just to compute the legacy hash.. but I want to avoid that as much as possible!
Thanks!
It looks like your perl code just concatenates the data with the salt, then hashes that - a4584f550a133a7f47cc9bafd84c9870
is simply the MD5 of "HelloWorld" + "12345678"
.
Rather than using HMACMD5, you just need to do something like this, using MD5:
using (MD5 a = MD5.Create()) {
byte[] bytes = Encoding.UTF8.GetBytes(data + salt);
byte[] hashed = a.ComputeHash(bytes);
var sb = new StringBuilder();
for (int i = 0; i < hashed.Length; i++) {
sb.Append(hashed[i].ToString("x2"));
}
Console.WriteLine(sb.ToString()); // a4584f550a133a7f47cc9bafd84c9870
}