gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:08:13 24 4
gpt4 key购买 nike

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

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 等。

最佳答案

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

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

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

PS> [byte[]] -split ('F54429' -replace '..', '0x$& ')
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('ToString', 'X2')
F54429
.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

关于powershell - 如何在 PowerShell 中将哈希字符串转换为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54543075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com