Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate SHA-256 of a byte array

Tags:

php

I have a string $concate in the following code. I calculated the byte array of the string as follows:

for($i = 0; $i < strlen($concate); $i++){
    $binary[] = ord($concate[$i]);
}

Now I want to calculate SHA-256 hash of the byte array, $binary, but I don't know how to do that. Would someone advise?

What i have to do is:-

  1. Calculate the binary (using utf-8 encoding) of a string(example - "hello world").

  2. Calculate SHA-256 of result of step 1.

  3. Calculate hexadecimal of the output of step 2.

like image 297
The Real Coder Avatar asked Oct 29 '25 11:10

The Real Coder


1 Answers

The string itself is in binary format. So hash('sha256', $concate) will be enough for this. If you want the output to be binary, set the third parameter to true.

$hash = hash('sha256', $concate, true); // or
$hash = hex2bin(hash('sha256', $concate)); // provides same output as above

It'll binary string instead of hex string.

See this example for illustration.

like image 100
Shiplu Mokaddim Avatar answered Nov 01 '25 02:11

Shiplu Mokaddim