Published: Fri 12 February 2016
By Jason
In PowerShell .
I needed a PowerShell script to generate a random alpha-numeric string. Here were my goals:
The randomness needs to be cryptographically strong.
Having at least some characters of different types is not a concern here.
Small-ish, readable code is a concern.
Here's what I came up with:
# Generate an random code or password
$code = ""
$codeLength = 26
$allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
$rng = new-object System . Security . Cryptography . RNGCryptoServiceProvider
$randomBytes = new-object "System.Byte[]" 1
# keep unbiased by making sure input range divides evenly by output range
$inputRange = $allowedChars . Length * [Math] :: Floor ( 256 / $allowedChars . Length )
while ( $code . Length -lt $codeLength ) {
$rng . GetBytes ( $randomBytes )
$byte = $randomBytes [ 0 ]
if ( $byte -lt $inputRange ) { # throw away out-of-range inputs
$code += $allowedChars [ $byte % $allowedChars . Length ]
}
}
# Here's the code/password:
$code
~~I realize this script throws away more bits than necessary, but improving that while keeping $allowedChars
flexible would add quite a few lines, and wasn't worth the sacrifice to requirement #3.~~
Thanks Dan Jenkins for helping me fix this with only one additional line of code!
I think it's solid, but am very open to feedback.
There are comments .
Proudly powered by Pelican , which takes great advantage of Python .
The theme is by Smashing Magazine , thanks!