Created
February 12, 2024 21:11
-
-
Save dreadsend/0abecfa2ef687ccebb499e9f297ee633 to your computer and use it in GitHub Desktop.
Function to Generate Password Hashes with a given Salt Value
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
function New-Pbkdf2Hash { | |
param ( | |
[Parameter(Mandatory = $true, Position = 0)] | |
[ValidateNotNull()] | |
[string]$toHash, | |
[Parameter(Mandatory = $true, Position = 1)] | |
[ValidateNotNull()] | |
[Securestring]$salt, | |
[Parameter(Mandatory = $false)] | |
[ValidateSet("SHA256","SHA3_256","SHA384","SHA3_384","SHA512","SHA3_512")] | |
[string]$hashAlg = "SHA512", | |
[Parameter(Mandatory = $false)] | |
[ValidateSet("lower","upper")] | |
[string]$standardCase, # Falls wir aufgrund von Händischen Einträgen / uneinheitlicher Datenquelle Case Sensitivity umgehen wollen | |
# Für Nutzung als Kennwort Speicher ist der Empfohlene Wert 210.000 Iterationen, aber dann dauert die Kalkulation schon ein paar Sekunden | |
# Das Kennwort wird in unserem Fall nicht gespeichert, sondern nur der initiale Wert generiert | |
[Parameter(Mandatory = $false)] | |
[int]$iterations = 1000, | |
[Parameter(Mandatory = $false)] | |
[int]$hashLength = 60 | |
) | |
switch ($standardCase) { | |
"lower" { $toHash = $toHash.ToLower() } | |
"upper" { $toHash = $toHash.ToUpper() } | |
} | |
try { | |
# Generieren des Hashes / Passwort und Konvertieren zu Securestring aus Byte Array | |
$saltBytes = [Text.Encoding]::UTF8.GetBytes([System.Net.NetworkCredential]::new("", $salt).Password) | |
# Die dedizierte Pbkdf2 Methode ist nur im vollen .NET Verfügbar, nicht .NET Framework | |
$hashResult = [System.Security.Cryptography.Rfc2898DeriveBytes]::new($toHash, $saltBytes, $iterations, $hashAlg) | |
$hashString = ConvertTo-Securestring "$( [System.Convert]::ToBase64String($hashResult.GetBytes($hashLength)) )" -AsPlainText -Force | |
} | |
catch { | |
Throw $_.Exception.Message | |
} | |
finally { | |
# Entfernen kritischer Werte aus dem Arbeitsspeicher | |
$sensitiveVars = @("saltBytes","hashResult") | |
Remove-Variable $sensitiveVars | |
[gc]::Collect() | |
} | |
return $hashString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment