Last active
May 13, 2022 14:53
-
-
Save santisq/95a4332f7acc58658945c667d572876d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Collections.Generic | |
class PasswordGen { | |
[int] $Length = 20 | |
[int] $NonAlphaCount = 7 | |
[string] $Password | |
PasswordGen () { | |
$this.GetNewPassword() | |
} | |
PasswordGen ([int] $Length, [int] $NonAlphaNumCount) { | |
$this.GetNewPassword($Length, $NonAlphaNumCount) | |
} | |
PasswordGen ([int] $Length) { | |
$this.GetNewPassword($Length, $this.NonAlphaCount) | |
} | |
[void] GetNewPassword() { | |
$this.GetNewPassword($this.Length, $this.NonAlphaCount) | |
} | |
[void] GetNewPassword([int] $Length, [int] $NonAlphaNumCount) { | |
if($Length -gt [int]::MaxValue / 20) { | |
throw [System.ArgumentException]::new( | |
'Length is too big!', | |
'Length' | |
) | |
} | |
if($Length -lt $NonAlphaNumCount) { | |
throw [System.ArgumentException]::new( | |
'Length cannot be lower than Non-Alphanumeric char count.', | |
'NonAlphaNumCount' | |
) | |
} | |
$this.Length = $Length | |
$this.NonAlphaCount = $NonAlphaNumCount | |
$CharSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' | |
$NonAlphaNum = '!@#$%^&*()_-+=[{]};:<>|./?' | |
$ran = [random]::new() | |
$passw = [char[]]::new($Length) | |
$charLength = $Length - $NonAlphaNumCount | |
for($i = 0; $i -lt $charLength; $i++) { | |
$passw[$i] = $CharSet[$ran.Next($CharSet.Length)] | |
} | |
for($i = $i; $i -lt $Length; $i++) { | |
$passw[$i] = $NonAlphaNum[$ran.Next($NonAlphaNum.Length)] | |
} | |
$this.Password = $this.Shuffle([string]::new($passw)) | |
} | |
[void] Shuffle() { | |
$this.Password = $this.Shuffle($this.Password) | |
} | |
[string] Shuffle ([string]$Passw) { | |
$ran = [random]::new() | |
$shuffled = [char[]]::new($Passw.Length) | |
$shuffle = [List[Char]]::new() | |
$shuffle.AddRange($Passw.ToCharArray()) | |
for($i = 0; $i -lt $Passw.Length; $i++) { | |
$item = $ran.Next($shuffle.Count) | |
$shuffled[$i] = $shuffle[$item] | |
$shuffle.RemoveAt($item) | |
} | |
return [string]::new($shuffled) | |
} | |
} | |
$p = [PasswordGen]::new() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment