Sep 18, 2013

Powershell - converting array output into string (OpenSSL ...)

In my specific example, I was trying to get OpenSSL output to show up as a string in the least amount of typing (this is for a class I'll be teaching), meaning each student would have to read the slide, and type what's on it. Meaning that each extra bracket of code students type, could result in some unpredictable disaster which would stop the whole class from moving forward. So, I wanted to come up with the most elegant way possible.


Example:
PS\> openssl rand -base64 512
vq6liIBbS0vy5XXUQiknc8Mw/Bzm5YwjYJKkv34wns0w7OGXcXpXN4mutLmlcJ7h
N7P8557UtZW2JPwhrh6KbrtqK6SzvQK0uZvAejt074gOS0yWkVvnQC6/y4GWpfkA
l93McZpiHB7dAUxglHWPdA2u3+wYfJMt4VkCYAFTqyDyFyRxhi9KWhRdE55OyZQz
P92tVM8Vjo7rQVroDdW/SvQTPklAzJcwbubuBCfXvENWwhcXFEOyLhjftoxSEojR
qTraYr5J6CfMs9ELedRKjEUgHeXcnarBf0BbjliDwzeVQ7DcFGeq6i4aRed4U+1X
OuH5ewOI2qqrY3sQtWnG52X2BYWhi8Bs0G6h1SVvn7LsCLO3HGjB/cyLcujYQpcv
HMw8EXXndOvSXMif/N66RjRbafn0ZNjlCB1KtdNIy8y7gPJCkf6UbJuypZGWHlnd
wktJV1L4S7kKNKyaDX+9tZoTiZhN50qTYFZ+dQ9E5ItIBxoHc5UuQvK334nm8y70
Czpq1lfj1S9CSEvkcCaMkOnZOx+mb1rPcIm4fg6pA+F10m1t4Eph4m3QLxY7H4RE
yfxsZhWbE+I/epsODOeVi3VzHzz3UuNKuA+RvLD2U8QGDgyl9DRIgKGmMaShN7oa
6+OWoKeX4spSCkFIPwuPlcLAkVSBDEIrwlAIi+9hQr8=

But what you really want is a string... The reason is, in Chef the data_bag object can be encrypted. So user names, password, data base keys are all safe and sound behind OpenSSL (pun retroactively intended). However, decrypt takes a string, and Powershell generates an array. So, I needed to convert array to string in powershell in the most elegant way possible.

I am not* going to bore you with the many failed attempts, so here is the best answer I came up with*:

PS\> -join $(openssl rand -base64 512)

Yup. That's it.

A really neat side effect, is that in every class I have a few people tell me this "join" is awesome and they had no idea it was possible.  This is why I dig what I do now.

* I didn't actually come up with the -join by itself, this dude here did: http://stackoverflow.com/questions/7723584/powershell-how-to-convert-array-object-to-string

I lied about not boring you... here are the various semi-failed attempts:

  •     [string]$(openssl rand -base64 512) -replace " ",""
  •     openssl rand -base64 512 | %{write-host $_ -NoNewline}
  •     Write-Host -Object $(openssl rand -base64 512) -Separator ""
  •     openssl rand -base64 512 | %{[string]$a+=$_}
  •     $result = $result -replace "`t|`n|`r",""
  •     ...this one is cool, but makes changes to $ofs:
              $ofs="";[string]$(openssl rand -base64 512)

No comments:

Post a Comment

Comments are welcomed and appreciated.