Diese Klasse generiert ein Passwort auf Grundlage gegebener Länge und gewünschter Zeichen.
Zudem ist möglich, zu einem gegebenen Passwort die Anzahl aller Zeichenketten, welche jenem Schema entsprechen, zu ermitteln.
'8 Ziffern: Zahlen, Klein- & Großbuchstaben außer {a,D,Z}
Dim passwort As String = Password.Generate(8, True, True, True, False, "", "aDZ")
'6 Ziffern: nur bestehend aus expliziten Zeichen {3,a,B,+}
Dim passwort As String = Password.Generate(6, False, False, False, False, "3aB+")
'
GetCombinations("1hallo") -> (10+26)^6 = 2176782336
GetCombinations("WORT") -> 26^4 = 456976
GetCombinations("+zahl") -> (32+26)^5 = 656356768
Aus ungültigen Eingaben wie Längen < 1 oder keine ausgewählten Zeichen resultiert ein leerer String. Diese Fehlerbehandlung ist durchaus ausbaufähig, doch hier gut ausreichend.
Public Class Password
Public Shared Function Generate(ByVal length As Byte, ByVal numbers As Boolean, _
ByVal lowerCases As Boolean, ByVal upperCases As Boolean, _
ByVal specials As Boolean, Optional ByVal include As String = "", _
Optional Byval exclude As String = "") As String
'password must contain at least one character from at least one subset
If length = 0 OrElse (Not (numbers OrElse lowerCases OrElse upperCases OrElse specials) AndAlso include = "") Then Return ""
'add selected characters
Dim random As New Random, charset As String = "", password As String = ""
If numbers Then charset &= "0123456789"
If lowerCases Then charset &= "abcdefghijklmnopqrstuvwxyz"
If upperCases Then charset &= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
If specials Then charset &= "+-/*#,;.:-_^!()[]{}=?ß'äÄöÖüÜ<>@"
'add/remove further ones
If Not include = "" Then charset &= include
If Not exclude = "" Then
For Each c As Char In exclude
charset = charset.Replace(c, "")
Next
End If
'create random password
For i As Byte = 1 To length
password &= charset(random.Next(0, charset.Length))
Next
Return password
End Function
Public Shared Function GetCombinations(ByVal password As String) As ULong
Dim nums, lows, upps, specs As New Boolean, combos As ULong = 0
For Each num As Char In "0123456789"
If password.Contains(num) Then combos += 10 : Exit For
Next
For Each low As Char In "abcdefghijklmnopqrstuvwxyz"
If password.Contains(low) Then combos += 26 : Exit For
Next
For Each upp As Char In "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
If password.Contains(upp) Then combos += 26 : Exit For
Next
For Each spec As Char In "+-/*#,;.:-_^!()[]{}=?ß'äÄöÖüÜ<>@"
If password.Contains(spec) Then combos += 32 : Exit For
Next
Return combos ^ password.Length
End Function
End Class