Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sha256 hash output as binary data instead of hex using powershell?

Is there an in-built method to generate SHA256 as a binary data for a given string ? Basically, I am using below bash script to first generate a hash as a binary data and then do a base64 encoding. All I want to have is the exact thing in Powershell so that both the outputs are identical:

clearString="test"
payloadDigest=`echo -n "$clearString" | openssl dgst -binary -sha256 | openssl base64 `
echo ${payloadDigest}

In powershell, I can get the SHA256 in hex using the below script, but then struggling to get it as a binary data:

$ClearString= "test"
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create('sha256')
$hash = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($ClearString))

$hashString = [System.BitConverter]::ToString($hash)
$256String= $hashString.Replace('-', '').ToLower()
$sha256String="(stdin)= "+$256String
$sha256String

I can then use [Convert]::ToBase64String($Bytes) to convert to base64 but in between how do I get a binary data similar to bash output before I pass it to base64 conversion.

like image 351
aashleo Avatar asked Nov 12 '19 09:11

aashleo


1 Answers

I think you are over-doing this, since the ComputeHash method already returns a Byte[] array (binary data). To do what (I think) you are trying to achieve, don't convert the bytes to string, because that will result in a hexadecimal string.

$ClearString= "test"
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create('sha256')
$hash = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($ClearString))
# $hash is a Byte[] array

# convert to Base64
[Convert]::ToBase64String($hash)

returns

n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=

like image 101
Theo Avatar answered Nov 16 '22 15:11

Theo