Reputation:
I have a string that needs to be hashed using a salt in C# and match what it would in PHP. The C# code is as follows:
string stringToHash = "123";
string saltToUse = "321";
byte[] stringBytes = ASCIIEncoding.ASCII.GetBytes(stringToHash);
byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(saltToUse);
var hmacMD5 = new HMACMD5(saltBytes);
var saltedHash = hmacMD5.ComputeHash(stringBytes);
byte[] hashedBytesNoSalt = MD5CryptoServiceProvider.Create().ComputeHash(stringBytes);
string hashedString = BitConverter.ToString(hashedBytesNoSalt).Replace("-", "").ToLower();
string saltedString = BitConverter.ToString(saltedHash).Replace("-", "").ToLower();
The PHP code to test if the C# is outputting correctly is:
<?php echo md5('123'.'321'); ?>
The C# outputs the correct UNSALTED MD5 hash, which is 202cb962ac59075b964b07152d234b70. However, when I try to salt using C# I get 900011ae860f471561023fba6cc25df6 and with PHP I get c8837b23ff8aaa8a2dde915473ce0991.
I am not sure why it is doing this or if this is even the correct way. The thing to remember is the C# needs to output to what the PHP outputs to.
Upvotes: 2
Views: 1303
Reputation: 34922
A salt is not the same thing as a private key. HMACMD5
uses a private key, when all that you desire is a salted MD5 hash. Just append the salt to the string to generate the correct key... stringToHash + saltToUse
.
Read about HMACMD5
here: http://msdn.microsoft.com/en-us/library/yd9e7dt2.aspx
Upvotes: 1
Reputation: 4228
The C# code is using a better salting mechanism than the PHP code. To match the PHP, all you need to do is run MD5 on stringToHash + saltToUse
instead of using the HMACMD5's key feature. In short, do exactly what you did to produce your unsalted MD5 in C#, but pass in stringToHash + saltToUse
instead.
Upvotes: 2