7
votes

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?

Thanks.

3

3 Answers

17
votes

You can use the X2 format string on each individual byte to get it's hex representation, then use the -join operator to concatenate the strings:

$bytes = 0,54,0,48,0,49,0,99,0,48,0,98,0,97,0,45,0,50,0,50,0,97,0,57,0,45,0,49,0,49,0,101
$hexString = ($bytes|ForEach-Object ToString X2) -join ''

(If that's your actual key, you might want to refrain from ever using it again, now that it's public knowledge ;-) )

6
votes

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.

0
votes

I think you forgot to use the header and footer used in ssl certificate files. They must be used for open ssl to recognize that it is an SSL certificate.