Encoding a Love Letters (and Other Things) in Hex Strings

by Oct 7, 2013

If your partner is as geeky as you, he or she may enjoy a private message in hex encoding. Everyone else may at least enjoy the technology used here, concatenating a number of type conversions:

$text = "This is my secret message"
-join ([Byte[]][Char[]]$text | ForEach-Object { '{0:x2}' -f $_ }) 

The text is converted to a character array, this is then converted into a byte array, and the bytes are finally converted to two-digit hex pairs which -join combines to something like this:

Which raises the question just how decode the message. Here's the trick:

-join $(foreach($hex in ('54686973206973206d7920736563726574206d657373616765' -split '(?<=\G[0-9a-f]{2})(?=.)'))
{ [Char][System.Convert]::ToByte($hex, 16) }) 

There are many use cases. For example, use the first code sample to encode some PowerShell command:

$text = 'Get-Service | Where-Object { $_.Status -eq "Running"}'
-join ([Byte[]][Char[]]$text | ForEach-Object { '{0:X2}' -f $_ }) | clip

Next, paste the hex codes into your second script, and feed the result to Invoke-Expression:

Invoke-Expression (-join $(foreach($hex in ('4765742D53657276696365207C2057686572652D4F626A656374207B20245F2E537461747573202D6571202252756E6E696E67227D' -split '(?<=\G[0-9a-f]{2})(?=.)'))
{ [Char][System.Convert]::ToByte($hex, 16) })) 

Now ask your colleagues what this would do! As it turns out, it simply runs the encoded command. In this case, it lists all running services.

Twitter This Tip! ReTweet this Tip!