I have a hashing method in C# that looks like:
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] raw_input = Encoding.UTF32.GetBytes("hello");
byte[] raw_output = md5.ComputeHash(raw_input);
string output = "";
foreach (byte myByte in raw_output)
output += myByte.ToString("X2");
return output;
How can I implement this in PHP? Doing the following produces a different hash digest...
$output = hash('md5', 'hello');
PHP
This PHP code will do:
<?php
$str = "admin";
$strUtf32 = mb_convert_encoding($str, "UTF-32LE");
echo md5($strUtf32);
?>
This code outputs "1e3fcd02b1547f847cb7fc3add4484a5"
You need to find out which encoding PHP is using to convert your string to text. It's very unlikely that it's using UTF-32. It may well be using the platform default encoding, or possibly UTF-8.
using (MD5 md5 = MD5.Create())
{
byte[] input = Encoding.UTF8.GetBytes("hello");
byte[] hash = md5.ComputeHash(input);
return BitConverter.ToString(hash).Replace("-", "");
}
(This is the problem with languages/platforms which treat strings as binary data all over the place - it doesn't make it clear what's going on. There has to be a conversion to bytes here, as MD5 is defined for bytes, not Unicode characters. In the C# code you're doing it explicitly... in the PHP it's implicit and poorly documented.)
EDIT: If you've got to change the PHP, you could try this:
$text = mb_convert_encoding($text, "UTF-32LE");
$output = md5($text)
It depends whether PHP supports UTF-32 though...
When you apply md5 to Encoding.UTF32.GetBytes("admin");, that's same as
echo hash( "md5","a\0\0\0d\0\0\0m\0\0\0i\0\0\0n\0\0\0");
//1e3fcd02b1547f847cb7fc3add4484a5
In php.
You need to convert your string to UTF32-LE in PHP:
echo md5( mb_convert_encoding( "admin", "UTF-32LE" ) );
//1e3fcd02b1547f847cb7fc3add4484a5
Related
I'm working on rewriting a piece of PHP code to C#. This code is used for password hashing. In the first step it produces a string like "password{salt}", than hashes it via sha512 hash algorithm. After that a loop is hashing the combination of the first hash and the salt again for 5000 iterations.
The PHP Code looks like this:
<?php
$password = 'abc';
$salt = 'def';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
for ($i=1; $i<5000; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
$encodedPassword = base64_encode($digest);
//$encodedPassword contains the final hash code
I was able to get it working without the loop (with just the first hash() call). So the main hashing and base64 encoding is done correctly. I found out that this part is what I cannot manage to rewrite in C#:
$digest.$salted
$digest seems to be a binary representation since PHP's hash() function was used with "true" as the last parameter (see PHP hash - manual). $salted is a string. Both get somehow magically combined by PHP's dot / concat operator. I guess there will be some sort of standard conversion from binary to string under the hood when using the dot operator with a non-string operand.
This is my code so far:
void Main()
{
string password = "abc";
string salt = "def";
string salted = String.Format("{0}{{{1}}}", password, salt);
byte[] digest = hash(salted);
for(int i = 1; i < 1; i++)
{
digest = hash(String.Format("{0}{1}", System.Text.Encoding.UTF8.GetString(digest), salted));
}
var encodedPassword = System.Convert.ToBase64String(digest);
//$encodedPassword should contain the final hash code
}
static byte[] hash(string toHash)
{
System.Security.Cryptography.SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();
return sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(toHash));
}
As you see I tried to convert the hash bytes back to a string with System.Text.Encoding.UTF8.GetString() and then append the salt but that doesn't produce the same output as the PHP code.
I would be very happy if someone could help me on this. Thank you very much.
In the PHP version you loop 4999 times, while in the C# version 0. The second problem is that the returned bytes from hash() have no encoding at all.
This should give you the same result as the PHP version:
System.Security.Cryptography.SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();
var saltedUtf8Bytes = System.Text.Encoding.UTF8.GetBytes(salted);
for(int i = 1; i < 5000; i++)
{
digest = sha512.ComputeHash(digest.Concat(saltedUtf8Bytes).ToArray());
}
This question already has answers here:
MD5 hashing does not match in C# and PHP
(2 answers)
Closed 5 years ago.
in C# I'm trying to get a hashed md5 value of a password like so:
string sb = textBox2.Text;
byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(sb);
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(sb);
sb = System.Convert.ToBase64String(plainTextBytes);
in php I get that value by using md5 command,
echo md5("megusia94");
the input in both cases are the same,
yet the output in PHP is: d1e44ad921daadaf8defadcd21c8644a
while in C# the output is: bWVndXMpYTk0
What am I doing wrong? I've searched this forum and tried:
MD5 hashing does not match in C# and PHP
c# md5 and php md5 not match
You are not comparing the same two things.
What you are comparing is the base64-representation of the ASCII-encoded input string with the actual MD5 hash (in HEX representation) from PHP.
Instead look at this:
byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes("megusia94");
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
Console.WriteLine(hashedString);
It correctly produces the hash d1e44ad921daadaf8defadcd21c8644a, which is the same as the one you get from PHP.
PHP md5:
Returns the hash as a 32-character hexadecimal number.
Your C# code:
Returns the hash with base64 encoding.
I have this code that I need to convert to ruby, this snippet is to create a security key used for a particular API. The string that I am encrypting is a JSON object.
Should I use Digest::MD5.hexdigest() or Digest::MD5.digest()?
C# Code
string strResponse = "[{\"Key\":\"BookNumber\", \"Value\"=>\"BJAK123\"},{\"Key\"=>\"AuthorCode\", \"Value\"=>\"BNA123\"}]";
using (MD5 md5 = MD5.Create())
{
byte[] bPayload = Encoding.UTF8.GetBytes(strPayload);
byte[] bPayloadHash = md5.ComputeHash(bPayload);
strPayloadBase64 = Convert.ToBase64String(bPayloadHash);
}
Ruby Code
payload = [{"Key"=>"BookNumber", "Value"=>"BJAK123"},{"Key"=>"AuthorCode", "Value"=>"BNA123"}]
utf8_params = payload.to_json.force_encoding("iso-8859-1").force_encoding("utf-8")
payload_base64 = Base64.encode64(Digest::MD5.hexdigest(utf8_params))
Use
payload_base64 = Digest::MD5.base64digest(utf8_params)
as Digest::MD5.hexdigest produces a hex string of digest, whereas C# code is performing base64 encoding of the digest.
This is my PHP code:
<?php
$sig_string = "GET&https%3A%2F%2Fapi.pinterest.com%2Fv3%2Fusers%2Farchimede%2Fboards%2F&client_id=987654×tamp=1391761866";
$secret = "123456";
$sig = hash_hmac("sha256", $sig_string, $secret);
echo $sig;
?>
which returns (correctly) a7918aec50919915f3cefed8622ddbe35448c8f71a54ad115828f07a05930f4c
Now, I want to translate this function inside C#. Code:
signature_base_string = "GET&https%3A%2F%2Fapi.pinterest.com%2Fv3%2Fusers%2Farchimede%2Fboards%2F&client_id=987654×tamp=1391761866";
signing_key = "123456";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(signing_key);
byte[] messageBytes = encoding.GetBytes(signature_base_string);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
Response.Write(Convert.ToBase64String(hashmessage));
}
but it retuns p5GK7FCRmRXzzv7YYi3b41RIyPcaVK0RWCjwegWTD0w=
Why two different results? Whats wrong in the C# code?
PHP encodes the result in hexadecimal and c# encodes that in base64. But the are same.
Change this line:
Response.Write(Convert.ToBase64String(hashmessage));
To this:
Response.Write(BitConverter.ToString(hashmessage).Replace("-", "").ToLower());
to have the result in hexadecimal encoding.
They are the same:
The result from .NET C# is p5GK7FCRmRXzzv7YYi3b41RIyPcaVK0RWCjwegWTD0w=. This is a base64 string.
You can convert it to hexadecimal using this tool for example. And you'll get the same as PHP after converting:
A7918AEC50919915F3CEFED8622DDBE35448C8F71A54AD115828F07A05930F4C
I am doing md-5 hashing in both android and c# at the same time. But both the results should be the same for the same inputs. Is there any difference in the way its done in both the languages?
I get different outputs in both the cases. Here is the c# code for md-5 calculation:
//this method hashes the values sent to it using MD5
public static String hashwithmd5(String toHashMD5)
{
byte[] keyArray;
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(toHashMD5));
hashmd5.Clear();
return Convert.ToBase64String(keyArray, 0, keyArray.Length);
}
and here is the code for md5 in android using bouncycastle
public byte[] Hashing(String toHash) throws Exception{
byte[] hashBytes = toHash.getBytes("UTF-8");
EditText et = (EditText) findViewById(R.id.entry);
org.bouncycastle.crypto.digests.MD5Digest digest = new org.bouncycastle.crypto.digests.MD5Digest();
digest.reset();
digest.update(hashBytes, 0, hashBytes.length);
int length = digest.getDigestSize();
byte[] md5 = new byte[length];
digest.doFinal(md5, 0);
et.setText(md5.toString());
return md5;
}
the result of md5 in c# is :XUFAKrxLKna5cZ2REBfFkg==
the result of md5 in android is :[B#4053cf40
The C# code converts the hash to Base64, the java code does not. If you convert both raw hashes to e.g. hex strings, they'll be the same.
When you use this in Java:
byte[] md5 = new byte[length];
// ...
md5.toString()
you are not getting a representation of the byte values. You get the generic "string representation" of an object. Here, [B#4053cf40 basically means "array of bytes (that's for the '[B') which internally happens to be at address 4053cf40".
Use android.util.Base64 to convert your bytes to a Base64 encoded string.
#erik is correct. MD5 is no longer considered a "secure" hash; use SHA-256.
Erik is absolutely right. MD5 usage is near extinction, use any strong SHA