Skip to content

Instantly share code, notes, and snippets.

@GoodOlClint
Created April 13, 2015 01:51
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 GoodOlClint/2ed06ef281d7b2e799b7 to your computer and use it in GitHub Desktop.
Save GoodOlClint/2ed06ef281d7b2e799b7 to your computer and use it in GitHub Desktop.
Generates a cryptographically strong password
function New-StrongPassword
{
<#
.SYNOPSIS
Returns a strong password of the specified length
.DESCRIPTION
Returns a strong password of the specified length
Uses the RNGCryptoServiceProvider to randomly select each character of the password
.PARAMETER Length
Length of password to generate
.PARAMETER NoNumbers
If set password will not contain numbers
.PARAMETER NoSpecial
If set password will not contain special characters: ~!@#$%^&*()
.PARAMETER AsSecureString
If set returns a System.Security.SecureString object containing the password
.EXAMPLE
PS C:\> New-StrongPassword 15
K*5@vp2RrL07COE
.EXAMPLE
PS C:\> New-StrongPassword -Length 15 -AsSecureString
System.Security.SecureString
.EXAMPLE
PS C:\> New-StrongPassword -Length 15 -NoNumbers
KMHrXl(cATGSOVp
.EXAMPLE
PS C:\> New-StrongPassword -Length 15 -NoSpecial
jSqciEAUdoYyj3R
.EXAMPLE
PS C:\> New-StrongPassword -Length 15 -NoNumbers -NoSpecial
MUaTnhIkwUcfcfW
#>
param(
[Parameter(Mandatory = $True)]
[int]$Length,
[switch]$NoNumbers,
[switch]$NoSpecial,
[switch]$AsSecureString
)
$Chars = @([char[]]"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if(-not $NoNumbers)
{ $Chars = $Chars + [char[]]"0123456789" }
if(-not $NoSpecial)
{ $Chars = $Chars + [char[]]"~!@#$%^&*()" }
$Crypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
[byte[]] $data = New-Object byte[] 1
$crypto.GetNonZeroBytes($data)
$data = New-Object byte[] $Length
$crypto.GetNonZeroBytes($data)
$string = New-Object System.Text.StringBuilder $Length
$secString = New-Object System.Security.SecureString
foreach ($b in $data)
{
if($AsSecureString)
{ $secString.AppendChar($Chars[$b % ($Chars.Length)]) }
else
{ $string.Append($Chars[$b % ($Chars.Length)]) | Out-Null }
}
if($AsSecureString)
{ return $secString }
else
{ return $string.ToString() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment