PowerShell: solid password generator

I needed a PowerShell script to generate a random alpha-numeric string. Here were my goals:

  1. The randomness needs to be cryptographically strong.
  2. Having at least some characters of different types is not a concern here.
  3. 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) {
    $byte = $randomBytes[0]
    if($byte -lt $inputRange) { # throw away out-of-range inputs
        $code += $allowedChars[$byte % $allowedChars.Length]

# Here's the code/password:

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.

This entry was posted in PowerShell, Programming. Bookmark the permalink.