How to convert a hash string to byte array in PowerShell?

Deadly 提交于 2020-05-12 04:37:46

问题


When my scripts run, I read a hash, and I would like to write it to the registry. I figured out that the following command will do it:

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

I also found the How to set a binary registry value (REG_BINARY) with PowerShell?.

However all answers suppose that the string is in form of:

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

but I only can read my hash in the following form:

"F5442930B1778ED31A....."

I can not figure out, how can I convert this to a byte array, with values F5, 44 etc.


回答1:


vonPryz sensibly suggests simply storing the hash directly as a string (REG_SZ) in the registry.

If you really want to store the data as type REG_BINARY, i.e., as an array of bytes, you must convert back and forth between the string representation.

To convert to a [byte[]] array (using a shortened sample hash string):

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

The above is PowerShell's default output representation of resulting array
[byte[]] (0xf5, 0x44, 0x29).


To convert from a [byte[]] array (back to a string; PSv4+ syntax):

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

.ForEach('ToString', 'X2') is the equivalent of calling .ToString('X2') - i.e., requesting a hex representation left-0-padded to 2 digits - on each array element and collecting the resulting string. -join then joins these strings to a single string by direct concatenation.


To put it all together:

# 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


来源:https://stackoverflow.com/questions/54543075/how-to-convert-a-hash-string-to-byte-array-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!