Question:
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:
1 2 3 4 |
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:
1 2 3 4 5 6 7 8 9 10 |
$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.
Answer:
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.
1 2 3 4 5 6 7 8 |
$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=