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

g.p*_*dou 4 registry powershell

当我的脚本运行时,我读取了一个哈希值,我想将它写入注册表。我发现以下命令可以做到:

New-ItemProperty  $RegPath -Name $AttrName -PropertyType Binary -Value $byteArray
Run Code Online (Sandbox Code Playgroud)

我还找到了如何使用 PowerShell 设置二进制注册表值 (REG_BINARY)?.

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

"50,33,01,00,00,00,00,00,...."
Run Code Online (Sandbox Code Playgroud)

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

"F5442930B1778ED31A....."
Run Code Online (Sandbox Code Playgroud)

我不知道如何将其转换为字节数组,其值为 F5、44 等。

mkl*_*nt0 13

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

如果您真的想将数据存储为 type REG_BINARY,即作为字节数组,则必须在字符串表示之间来回转换。

为了转换一个[byte[]]阵列(使用缩短的散列样本串):

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

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


为了转换一个[byte[]]阵列(回字符串; PSv4 +语法):

PS> -join ([byte[]] (0xf5, 0x44, 0x29)).ForEach('ToString', 'X2')
F54429
Run Code Online (Sandbox Code Playgroud)

.ForEach('ToString', 'X2')相当于在每个数组元素上调用.ToString('X2')- 即,请求左侧的十六进制表示0- 填充到 2 位数字 - 并收集结果字符串。-join然后通过直接连接将这些字符串连接成单个字符串。


把它们放在一起:

# 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('ToString', 'X2')

# (Clean up.)
Remove-ItemProperty -LiteralPath HKCU:\ -Name tmp
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

4972 次

最近记录:

4 年,6 月 前