6

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.

1
  • $hasher.ComputeHash() returns a Byte[] array, so you can just do [Convert]::ToBase64String($hash) if I'm not mistaken. By doing [System.BitConverter]::ToString($hash) you are converting the binary data into a hex string. Commented Nov 12, 2019 at 9:50

1 Answer 1

7

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=

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Theo, this was very helpful. I see where I went wrong now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.