Skip to content

Instantly share code, notes, and snippets.

@natesilva
Created December 10, 2018 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natesilva/495b334a6b70f4c5408eed6611bf037c to your computer and use it in GitHub Desktop.
Save natesilva/495b334a6b70f4c5408eed6611bf037c to your computer and use it in GitHub Desktop.
Command-line password generator
<#
.SYNOPSIS
CLI password generator using RNGCryptoServiceProvider
.DESCRIPTION
Generates a password at the command-line using a cryptographically-secure random
number generator.
.PARAMETER Length
How long of a password to generate.
.PARAMETER Chars
Chars from which to generate the password. The default set avoids ambiguous characters
(e.g. uppercase i and lowercase L).
.Parameter CopyToClipboard
Copy the password to the clipboard.
.EXAMPLE
mkpw
Generate a password
.EXAMPLE
mkpw 20
Generate a 20-character password
.EXAMPLE
mkpw -Length 64 -Chars abcdef0123456789
Generate a 64 character (32-byte) hexadecimal string
#>
param(
[ValidateRange(1, 1000)]
[Int]
$Length = 16,
[ValidateLength(1, 255)]
[String]
$Chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789",
[switch]
$CopyToClipboard = $false
)
$result = ""
$rnd = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$byte = New-Object System.Byte[] 1
while ($result.Length -lt $Length) {
# Note: avoids modulo bias
do {
$rnd.GetBytes($byte)
} while ($byte[0] -ge (255 - 255 % $Chars.Length))
$result += $Chars[$byte[0] % $Chars.Length]
}
if ($CopyToClipboard) {
$result | Set-Clipboard
}
$result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment