Powershell byte array to hex

Viewed 18951

I have the following byte array that I would like to obtain hex format in order to decrypt an encrypted string using aes-256-ecb. (PowerShell uses AES encryption if you specify key argument in ConvertFrom-SecureString function)

In order to check this I verify by using openssl:

echo 'mysecretdata' | openssl enc -d -aes-256-ecb -K 303534303438303439303939303438303938303937303435303530303530303937303537303435303439303439303130310a

hex string is too long invalid hex key value

What am I missing?

2 Answers

You can use the string System.BitConverter::ToString(byte[] value) static method if you're fine with hyphenation:

PS> $bytes = 0,7,14,21,28,35,42
PS> [System.BitConverter]::ToString($bytes)
00-07-0E-15-1C-23-2A
PS>
PS> # If you'd like to use this in a pipeline:
PS> ,$bytes | % { [System.BitConverter]::ToString($_) }
00-07-0E-15-1C-23-2A
PS>
PS> # If you can't obtain a byte[]-compatible input:
PS> $bytes | . { [System.BitConverter]::ToString(@($input)) }
00-07-0E-15-1C-23-2A

The comma operator (,) makes sure that your byte array (or object castable to such) is passed in (via ForEach-Object (%) running the script block over a 1-element array) as it is, and not iterated over.

If that's unavoidable, then the latter example uses the dot sourcing operator (.), a script block, and the array subexpression operator (@( )) to collect the items from the $input automatic function variable (an IEnumerator, not IEnumerable) and produce an array ToString's happy with.

Related