如何在PowerShell中将哈希字符串转换为字节数组?

问题描述 投票:2回答:1

当我的脚本运行时,我读了一个哈希,我想把它写到注册表中。我发现以下命令会这样做:

New-ItemProperty  $RegPath -Name $AttrName -PropertyType Binary -Value $byteArray

我也找到了How to set a binary registry value (REG_BINARY) with PowerShell?

但是,所有答案都假设字符串的形式为:

"50,33,01,00,00,00,00,00,...."

但我只能用以下形式读取我的哈希:

"F5442930B1778ED31A....."

我无法弄清楚,如何将其转换为字节数组,值为F5,44等。

powershell registry
1个回答
2
投票

vonPryz明智地建议简单地将哈希直接存储为注册表中的字符串(REG_SZ)。

如果您确实希望将数据存储为类型REG_BINARY,即作为字节数组,则必须在字符串表示之间来回转换。

要转换为[byte[]]数组(使用缩短的示例哈希字符串):

PS> [byte[]] ('F54429' -replace '..', '0x$&,' -split ',' -ne '')
245 # 1st byte: decimal representation of 0xF5
68  # 2nd byte: decimal representation of 0x44
41  # ...

以上是PowerShell的结果数组的默认输出表示 [byte[]] (0xf5, 0x44, 0x29)


要从[byte[]]数组转换(返回字符串; PSv4 +语法):

PS> -join ([byte[]] (0xf5, 0x44, 0x29)).ForEach({ '{0:X}' -f $_ })
F54429

把它们放在一起:

# Sample hash string.
$hashString = 'F54429'

# Convert the hash string to a byte array.
$hashByteArray = [byte[]] ($hashString -replace '..', '0x$&,' -split ',' -ne '')

# Create a REG_BINARY registry value from the byte array.
Set-ItemProperty -LiteralPath HKCU:\ -Name tmp -Type Binary -Value $hashByteArray

# Read the byte array back from the registry (PSv5+)
$hashByteArray2 = Get-ItemPropertyValue -LiteralPath HKCU:\ -Name tmp

# Convert it back to a string.
$hashString2 = -join $hashByteArray2.ForEach({ '{0:X}' -f $_ })

# (Clean up.)
Remove-ItemProperty -LiteralPath HKCU:\ -Name tmp
© www.soinside.com 2019 - 2024. All rights reserved.