BaltoStar
BaltoStar

Reputation: 8997

PS SHA512 hash of file, output as base 64 encoded string

I need to take the SHA512 of a file , convert to base 64 encoded string, and output to file.

PS > Get-FileHash <path to file> -Algorithm SHA512

I know this function is available [System.Convert]::ToBase64String

Upvotes: 4

Views: 4132

Answers (1)

boxdog
boxdog

Reputation: 8442

You can do it like this:

# Get the hash of the file
$hash = Get-FileHash <path to input file> -Algorithm SHA512

# Convert hash to byte representation
$hashBytes = [System.Text.Encoding]::Unicode.GetBytes($hash.Hash)

# Convert bytes to base64, then output to file
[System.Convert]::ToBase64String($hashBytes) | Out-File <path to hash output file>

Recover the hash again by doing this:

# Read encoded string from text file
$encodedHash = Get-Content <path to hash output file>

# Convert to from base64 to byte representation
$hashBytes = [System.Convert]::FromBase64String($encodedHash)

# Convert bytes to hash string
[System.Text.Encoding]::Unicode.GetString($hashBytes)

You can probably combine some of these steps, but this gives you a picture of the required steps

Upvotes: 3

Related Questions