I learned something new last Friday as well as had another idea driven home again. I like it when that happens. It’s odd to learn something yet periodically “realize” it all over again when life has need of that lesson.
I started working again on a scripting promise I made a while ago about sharing the ability to run an encrypted script without having to write the unencrypted contents to disk, thus making the contents of your script more secure. I’ve had the concept in my head and most of the proof it could be done, I just have to work on one very irritating issue with arrays. The other thing I needed to work on, and solved, was generating a random string. PowerShell has a native cmdlet to get a random number but not one for a string. I needed a string, so that I could randomly generate the IV that goes with each script. It’s generally accepted that knowing the IV doesn’t make it less secure so hard coding it to the resultant script isn’t a bad thing. However, it IS bad to always use the same IV. I figured it couldn’t be hard to write a simple function to generate a random string; it really wasn’t. Initially it was frustrating, though.
I started out with the idea I could use the get-random to randomly generate a 0 or 1 and then loop through that 8 times to generate an 8 bit binary code that I could then convert to a string. Figuring out how to make that 8 bit binary code into a string took a bit, and required multiple conversions of the data. My searching proved more fruitful than I intended. The one thing I learned was all of the different conversion methods available via .NET. Specifically, converting characters from decimal/hex/binary to whichever form is needed. It makes sense that they exist now that I think about it, but at the time I had never had a need for them and didn’t know they existed. This lead me to my recurring life lesson: it’s most invaluable being able to think differently. What could have continued to be difficult and maybe (for all intents and purposes) impossible, became an elegant solution just because I started to look at my situation from a different point of view.
I didn’t need to generate a rand byte of 1’s and 0’s because each ASCII character also has a decimal (and hex) value as well. So instead of using get-random 8 times to produce 1 ASCII char, I just needed to use it once to generate it’s decimal value. I didn’t want the non-character values in ASCII so I gave it the range of 33-127. The get-random does not include the max number (127, which is DEL and I don’t want) but it does include the minimum, 33 (which I do want and is !). I don’t know why it behaves this way.. it doesn’t make any sense.
The final\ script, below, ended up being only half the lines of the previous, unfinished script. I hope you find it useful. To use it, you just call the function and pass it the number of characters you want to use. ex) create-randomString 32