07-21-2023, 07:51 PM
using @YourWishIsMine answer, I created a simple function that supports all the algorithms for a string input. Because the types follow a specific naming convention, this can be easily extended to future algorithms by simply adding to the "ValidateSet" without any further code changes.
I also added pipeline support as well.
function ConvertTo-HashString
{
param (
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)][string]$value,
[ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512")][string]$Algorithm="SHA256"
)
process {
foreach ($v in $value)
{
$TypeName = "System.Security.Cryptography.{0}CryptoServiceProvider" -f $Algorithm
#check the algorithm to ensure its a valid type, for ValidateSet
if (-not ($typename -as [Type])) {
throw "Invalid Algorithm $Algorithm"
}
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($v)
$hash = ([System.BitConverter]::ToString((New-Object -TypeName $TypeName).ComputeHash($Bytes))).Replace("-","")
write-output $hash;
}
}
}
example usage:
ConvertTo-HashString -value 'hello world' -Algorithm sha256
B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9
ConvertTo-HashString -value 'hello world' -Algorithm sha512
309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
@('a','b','c') | ConvertTo-HashString -Algorithm SHA256
CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB
3E23E8160039594A33894F6564E1B1348BBD7A0088D42C4ACB73EEAED59C009D
2E7D2C03A9507AE265ECF5B5356885A53393A2029D241394997265A1A25AEFC6
I also added pipeline support as well.
function ConvertTo-HashString
{
param (
[Parameter(Mandatory=$true,ValueFromPipeLine=$true)][string]$value,
[ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512")][string]$Algorithm="SHA256"
)
process {
foreach ($v in $value)
{
$TypeName = "System.Security.Cryptography.{0}CryptoServiceProvider" -f $Algorithm
#check the algorithm to ensure its a valid type, for ValidateSet
if (-not ($typename -as [Type])) {
throw "Invalid Algorithm $Algorithm"
}
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($v)
$hash = ([System.BitConverter]::ToString((New-Object -TypeName $TypeName).ComputeHash($Bytes))).Replace("-","")
write-output $hash;
}
}
}
example usage:
ConvertTo-HashString -value 'hello world' -Algorithm sha256
B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9
ConvertTo-HashString -value 'hello world' -Algorithm sha512
309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
@('a','b','c') | ConvertTo-HashString -Algorithm SHA256
CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB
3E23E8160039594A33894F6564E1B1348BBD7A0088D42C4ACB73EEAED59C009D
2E7D2C03A9507AE265ECF5B5356885A53393A2029D241394997265A1A25AEFC6