Skip to content

Instantly share code, notes, and snippets.

@half-ogre
Created January 26, 2011 04:27
Show Gist options
  • Save half-ogre/796224 to your computer and use it in GitHub Desktop.
Save half-ogre/796224 to your computer and use it in GitHub Desktop.
I often need to get a hash with a random salt (usually for passwords) for the projects I work on. This is the PS script I use.
function Get-SaltedHash {
param($text)
$csp = new-object System.Security.Cryptography.RNGCryptoServiceProvider
$hashAlgorithm = new-object System.Security.Cryptography.SHA256Managed
$saltBytes = new-object byte[] 8
$csp.GetNonZeroBytes($saltBytes)
$textBytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$saltedTextBytes = new-object byte[] ($saltBytes.Length + $textBytes.Length)
[Array]::Copy($saltBytes, $saltedTextBytes, $saltBytes.Length)
[Array]::Copy($textBytes, 0, $saltedTextBytes, $saltBytes.Length, $textBytes.Length)
$hashBytes = $hashAlgorithm.ComputeHash($saltedTextBytes);
$saltPlusHashBytes = new-object byte[] ($saltBytes.Length + $hashBytes.Length)
[Array]::Copy($saltBytes, $saltPlusHashBytes, $saltBytes.Length)
[Array]::Copy($hashBytes, 0, $saltPlusHashBytes, $saltBytes.Length, $hashBytes.Length)
$saltedHash = [Convert]::ToBase64String($saltPlusHashBytes)
return $saltedHash
}
function Verify-SaltedHash {
param($hash, $text)
$hashAlgorithm = new-object System.Security.Cryptography.SHA256Managed
$saltPlusHashBytes = [Convert]::FromBase64String($hash);
$saltBytes = new-object byte[] 8
$hashToValidateBytes = new-object byte[] ($saltPlusHashBytes.Length - 8)
[Array]::Copy($saltPlusHashBytes, $saltBytes, 8)
[Array]::Copy($saltPlusHashBytes, 8, $hashToValidateBytes, 0, $hashToValidateBytes.Length)
$textBytes = [System.Text.Encoding]::UTF8.GetBytes($text);
$saltedTextBytes = new-object byte[] ($saltBytes.Length + $textBytes.Length)
[Array]::Copy($saltBytes, $saltedTextBytes, $saltBytes.Length)
[Array]::Copy($textBytes, 0, $saltedTextBytes, $saltBytes.Length, $textBytes.Length)
$hashBytes = $hashAlgorithm.ComputeHash($saltedTextBytes);
for ($i = 0; $i -lt $hashBytes.Length; $i++) {
if ($hashBytes[$i].Equals($hashToValidateBytes[$i]) -ne $true) {
return $false
}
}
return $true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment