Skip to content

Instantly share code, notes, and snippets.

@BrandonStiff
Last active April 19, 2017 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrandonStiff/91a6450695600cbc00b1679c4d7c325f to your computer and use it in GitHub Desktop.
Save BrandonStiff/91a6450695600cbc00b1679c4d7c325f to your computer and use it in GitHub Desktop.
Import a PowerShell Credential
function Import-PSCredential
{
<#
.SYNOPSIS
Imports a credential exported by Export-PSCredential and returns a Credential.
.PARAMETER Path
Specifies one or more files to convert from XML files to credentials.
.PARAMETER RegistryPath
Specifies the path in the registry to look for the encrypted credentials.
.PARAMETER Name
Specifies the registry key the credentials are stored under.
.PARAMETER KeyPhrase
Specifies the key phrase to use to encrypt the password. If not specified, then a key derived from the user's account is used. This makes the password only decryptable by the user who encrypted it.
If a key is specified, then anybody with the key can decrypt it.
.EXAMPLE
Import-PSCredential -Path C:\temp\mycreds.xml
# Retrieves encrypted credenials from the given file.
.EXAMPLE
Get-ChildItem C:\temp\credstore | Import-PSCredential
# Retrieves encrypted credenials from files in the given directory.
.EXAMPLE
Import-PSCredential -RegistryPath "HKCU:\Software\Acme Inc\MyCreds" -Name switch1
# Retrieves encrypted credenials from the registry path: "HKCU:\Software\Acme Inc\MyCreds" Key switch1
.EXAMPLE
Import-PSCredential -Path C:\temp\mycreds.xml -KeyPhrase "test12345"
# Retrieves encrypted credenials from the filesystem. Decrypts them using the given key.
.OUTPUTS
[System.Management.Automation.Credential]
Outputs a credential object representing the cached credentials. Use GetPlainTextPassword() to retrieve the plain text password.
#>
[CmdletBinding(DefaultParameterSetName="filesystem")]
param
(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="filesystem")]
[ValidateScript({ Test-Path -Path $_ -PathType Leaf } )] [String[]] $Path,
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="registry")]
[string] $RegistryPath,
[Parameter(Mandatory=$true,ParameterSetName="registry")]
[string] $Name,
[string] $KeyPhrase
)
begin
{
$paths = @()
}
process
{
if ( $PSCmdlet.ParameterSetName -ieq "registry" )
{
$paths += $RegistryPath
}
else
{
$paths += $Path
}
foreach ( $p in $paths )
{
$import = $null
if ( $PSCmdlet.ParameterSetName -ieq "registry" )
{
# Imported from registry:
$import = "" | Select-Object "UserName","EncryptedPassword"
# Make sure the registry key exists:
if ( Test-Path -Path $p )
{
$regValue = Get-ItemProperty -Path $p | Where-Object { $_.$Name }
if ( $regValue )
{
$credsAsString = (Get-ItemProperty -Path $p).$Name
if ( ($credsAsString -split ":").Count -lt 2 )
{
throw ("Credential was stored in an invalid format!")
}
$import.UserName = ($credsAsString -split ":")[0]
$import.EncryptedPassword = ($credsAsString -split ":")[1]
}
}
}
else
{
$fileFullPath = $p
if ( $p -is [System.IO.FileInfo] )
{
$fileFullPath = $p.FullName
}
# Import credential file
$import = Import-Clixml $fileFullPath
}
if ( $import -and $import.UserName -and $import.EncryptedPassword )
{
$userName = $import.Username
# Decrypt the password and store as a SecureString object for safekeeping
try
{
$params = @{};
if ( $KeyPhrase )
{
$params.Add("Key",(Get-EncryptionKey -KeyPhrase $KeyPhrase));
}
$securePass = $import.EncryptedPassword | ConvertTo-SecureString -ErrorAction Stop @params;
}
catch [System.FormatException]
{
throw ("An invalid encryption key was supplied! If this credential was encrypted with a KeyPhrase, you must use the correct keyphrase to decrypt it!");
}
catch [System.Security.Cryptography.CryptographicException]
{
throw ("Invalid encryption key! If no key is specified, then only the user that exported the credential in file $fileFullPath can retrieve it! Current user $($env:UserDomain)\$($env:UserName) may not have access!");
}
catch
{
throw $_;
}
# Build the new credential object
Get-PSCredential -Credential (New-Object System.Management.Automation.PSCredential $userName, $securePass);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment