The Real Coder
The Real Coder

Reputation: 138

Calculate SHA-256 of a byte array

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.

Upvotes: 4

Views: 7977

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

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.

Upvotes: 10

Michael
Michael

Reputation: 920

You can store binary data in a PHP-string. There is no need to convert it into a byte array. I think this is what you're looking for.

echo hash('sha256', $concate);

Upvotes: 0

Related Questions