Skip to content

Instantly share code, notes, and snippets.

@ianphil
Created June 27, 2016 15:06
Show Gist options
  • Save ianphil/b5e051cd1c34de95a693a633737a6ae1 to your computer and use it in GitHub Desktop.
Save ianphil/b5e051cd1c34de95a693a633737a6ae1 to your computer and use it in GitHub Desktop.
Read and Write passwords securely from PowerShell
function New-PasswordFile {
param($cert)
try {
$secureString = Read-Host -Prompt 'Enter password...' -AsSecureString
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
$key = New-Object byte[](32)
$rng.GetBytes($key)
$encryptedSecureString = ConvertFrom-SecureString -SecureString $secureString -Key $key
$encryptedKey = New-Object psobject -Property @{
Thumbprint = $cert.Thumbprint
Key = $cert.PublicKey.Key.Encrypt($key, $true)
}
$outputObject = New-Object psobject -Property @{
Payload = $encryptedSecureString
KeyInfo = $encryptedKey
}
$outputObject | Export-Clixml -Path C:\tools\password.xml
Write-Host 'Created file C:\tools\password.xml'
}
finally {
if ($null -ne $key)
{
[array]::Clear($key, 0, $key.Length)
$key = $null
}
}
}
function Get-CredentialFromFile {
param($cert)
try {
$object = Import-Clixml -Path C:\tools\password.xml
$key = $null
if ($cert.Thumbprint -eq $object.KeyInfo.Thumbprint) {
$key = $cert.PrivateKey.Decrypt($object.KeyInfo.Key, $true)
}
else {
Write-Error "No certificate matching thumbprint '$($cert.Thumbprint)' was used to protect the data."
}
$secureString = ConvertTo-SecureString -String $object.Payload -Key $key
$cred = New-Object System.Management.Automation.PSCredential('ianphil@microsoft.com', $secureString)
return $cred
}
finally {
if ($null -ne $key)
{
[array]::Clear($key, 0, $key.Length)
$key = $null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment