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

后端 未结 1 1948
醉话见心
醉话见心 2021-01-06 07:53

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  $Reg         


        
相关标签:
1条回答
  • 2021-01-06 08:21

    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
    
    0 讨论(0)
提交回复
热议问题