Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to hash a byte array in PHP but it is different from C# function ComputeHash

Input byte array:
10 241 161 2 121 5 228 157 20 19 2 7

Expected result (From C#):
91 110 159 77 220 148 223 78 194 210 64 197 147 127 162 229 47 142 1 130 47 252 238 232 126 74 108 91 241 253 242 31
Hash value: 5B6E9F4DDC94DF4EC2D240C5937FA2E52F8E01822FFCEEE87E4A6C5BF1FDF21F

Result from PHP:
398d3d7037eff6ed07ce7d39799a1c9abc240b59a07f79e64acfd36cbcfee422


What I have tried:

C# code:
byte[] byteArray = new byte[] {10, 241, 161, 2, 121, 5, 228, 157, 20, 19, 2, 7};
byte[] hashedBytes = algorithm.ComputeHash(byteArray);

PHP Code:
$arr = array(10,241,161,2,121,5,228,157,20,19,2,7);
$original = implode("", $arr);
hash('sha256', $original);
Posted
Updated 6-Feb-19 23:35pm

1 solution

This is because you're not hashing the same thing, in PHP you're turning it into a string with implode. For example, if you also turn it into a string in c# you get the same result as in php:

using System;
using System.Security.Cryptography;	
using System.Text;

public class Program
{
	public static void Main()
	{
		 using (SHA256 sha256Hash = SHA256.Create())
        {
		string str = "1024116121215228157201927";
		byte[] hashedBytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(str));
			 
			 for (int i = 0; i < hashedBytes.Length; i++)
        {
            Console.Write(hashedBytes[i].ToString("x2"));
        }
		 }
	}
}


And

<?php

$arr = array(10,241,161,2,121,5,228,157,20,19,2,7);
$original = implode("", $arr);
echo(hash('sha256', $original));

?>


Both give
6d615f5fd3e0a50c05520bccdb048f6fa4e2ae90788bda2379364d6cd1dcc707
 
Share this answer
 
v2
Comments
CPallini 7-Feb-19 6:13am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900