Carbon.Cryptography.psm1

# Copyright Aaron Jensen and WebMD Health Services
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

#Requires -Version 5.1
Set-StrictMode -Version 'Latest'

Add-Type -AssemblyName 'System.Security'

# Functions should use $moduleRoot as the relative root from which to find
# things. A published module has its function appended to this file, while a
# module in development has its functions in the Functions directory.
$moduleRoot = $PSScriptRoot
$moduleBinRoot = Join-Path -Path $moduleRoot -ChildPath 'bin'
$moduleBinRoot | Out-Null # To make the PSScriptAnalyzer squiggle go away.
$privateModulesRoot = Join-Path -Path $moduleRoot -ChildPath 'Modules'

Import-Module -Name (Join-Path -Path $privateModulesRoot -ChildPath 'Carbon.Core')

# Store each of your module's functions in its own file in the Functions
# directory. On the build server, your module's functions will be appended to
# this file, so only dot-source files that exist on the file system. This allows
# developers to work on a module without having to build it first. Grab all the
# functions that are in their own files.
$functionsPath = Join-Path -Path $moduleRoot -ChildPath 'Functions\*.ps1'
if( (Test-Path -Path $functionsPath) )
{
    foreach( $functionPath in (Get-Item $functionsPath) )
    {
        . $functionPath.FullName
    }
}



function Convert-CSecureStringToByte
{
    <#
    .SYNOPSIS
    Converts a secure string to an array of bytes.
 
    .DESCRIPTION
    The `Convert-CSecureStringToByte` converts a `[securestring]` to an array of bytes that represents the original
    decrypted string. The secure string is never left in memory as a string, but is kept as an array of bytes during
    the conversion, and all arrays used during the conversion are cleared.
 
    The decrypted secure string is returned as an array of bytes. You are resonsible for clearing the array when
    you're done, otherwise you risk exposing your secret in memory or on the file system.
 
    .EXAMPLE
    Convert-CSecureStringToByte -SecureString $credential.Password
 
    Demonstrates how to convert a secure string into an array of bytes representing the original password.
    #>

    [CmdletBinding()]
    [OutputType([Byte[]])]
    param(
        [Parameter(Mandatory)]
        [securestring]$SecureString
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $ptrDecryptedString = [Runtime.Interopservices.Marshal]::SecureStringToGlobalAllocUnicode($SecureString);
    try
    {
        [byte[]]$bytes = [byte[]]::New($SecureString.Length * 2)
        for( $idx = 0; $idx -lt $bytes.Length; ++$idx )
        {
            $bytes[$idx] = [Runtime.InteropServices.Marshal]::ReadByte($ptrDecryptedString, $idx)
        }
        return $bytes
    }
    finally
    {
        [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptrDecryptedString)
    }
}


function Convert-CSecureStringToString
{
    <#
    .SYNOPSIS
    Converts a secure string into a plain text string.
 
    .DESCRIPTION
    The `Convert-CSecureStringToString` function converts a secure string to a plaintexxt string. Try really, really,
    really hard not to do this. Once you do, the plaintext string will be *all over memory* and, perhaps, the file
    system.
     
    The function creates a new `[pscredential]` with the password and uses it to convert the password to plaintext
    (i.e. it calls `$credential.GetNetworkCredential().Password`).
 
    .OUTPUTS
    System.String.
 
    .EXAMPLE
    Convert-CSecureStringToString -SecureString $mySuperSecretPasswordIAmAboutToExposeToEveryone
 
    Returns the plain text/decrypted value of the secure string.
 
    .EXAMPLE
    $ISureHopeIKnowWhatIAmDoing | Convert-CSecureStringToString
 
    Demonstrates that you can pipe a secure string to `Convert-CSecureStringToString`.
    #>

    [CmdletBinding()]
    [OutputType([String])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        # The secure string to convert.
        [securestring]$SecureString
    )
    
    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        $bytes = Convert-CSecureStringToByte -SecureString $SecureString
        try
        {
            return [Text.Encoding]::Unicode.GetString($bytes)
        }
        finally
        {
            $bytes.Clear()
        }
    }
}




function ConvertTo-AesKey
{
    [CmdletBinding()]
    [OutputType([byte[]])]
    param(
        [Parameter(Mandatory)]
        [String]$From,

        [Parameter(Mandatory)]
        [Object]$InputObject
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState    

    $Key = $InputObject

    $bytesKey = $true
    if( $InputObject -isnot [byte[]] )
    {
        $bytesKey = $false
        if( $InputObject -is [SecureString] )
        {
            $unicodeKey = Convert-CSecureStringToByte -SecureString $InputObject
            try
            {
                # SecureString is two bytes per char. We need an encoding that is typically one byte per char, otherwise
                # the key will be twice as big as it should be. In the end, the user is responsible for ensuring the
                # key is the property size (in bytes).
                $Key = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeKey)
            }
            finally
            {
                $unicodeKey.Clear() # Keep it out of memory!
            }
        }
        else
        {
            $msg = "An encryption key must be a [securestring] or an array of bytes, but $($From) got passed a " +
                   """$($InputObject.GetType().FullName)"". If you are passing an array of bytes, make sure you " +
                   "explicitly cast it as a ``byte[]`, e.g. `([byte[]])@( ... )` when passing to $($From)."
            Write-Error -Message $msg
            return
        }
    }

    if( $Key.Length -ne 128/8 -and $Key.Length -ne 192/8 -and $Key.Length -ne 256/8 )
    {
        $commonMsg = "Key is the wrong length. The $($From) function is using AES, which requires a 128-bit, " +
                     '192-bit, or 256-bit key (16, 24, or 32 bytes, respectively). '
        # Did we receive an array of bytes for a key or a secure string?
        if( $bytesKey )
        {
            $msg = "$($commonMsg) Make sure your byte array key is 16, 24, or 32 bytes long."
        }
        # Got a secure string.
        else
        {
            $msg = "$($commonMsg) Make sure that when the secure string key is UTF-8 encoded and converted to a byte " +
                   "array, that array is 16, 32, or 64 bytes long. $($From) received a secure string key that is " +
                   "$($Key.Length) bytes long."
        }
        Write-Error -Message $msg
        return
    }

    return $Key
}



function Get-CCertificate
{
    <#
    .SYNOPSIS
    Gets a certificate from a file or the Windows certificate store.
 
    .DESCRIPTION
    The `Get-CCertificate` function gets an X509 certificate from a file or the Windows certificate store. When you
    want to get a certificate from a file, pass the path to the `Path` parameter (wildcards allowed). If the certificate
    is password-protected, pass its password, as a `[securestring]`, to the `Password` parameter. If you plan on
    installing the certificate in a Windows certificate store, and you want to customize the key storage flags, pass
    the flags to the `KeyStorageFlags` parameter.
 
    If the path is to a certificate in PowerShell's certificate drive (i.e. the path begins with `cert:\`), the
    `Password` and `KeyStorageFlags` are ignored. The certificate is returned. Wildcards allowed.
 
    You can search the Windows certificate stores for a certificate a specific thumbprint or friendly name by passing
    with the `Thumbprint` and `FriendlyName` parameters, respectively. `Get-CCertificate` will search all stores for all
    locations. If you know the store or location of the certificate, pass those to the `StoreName` and `StoreLocation`
    parameters, respectively. If the certificate is in a custom store, pass the store's name to the `CustomStoreName`
    parameter.
 
    `Get-CCertificate` adds a `Path` parameter which is the path where the certificate was loaded from the file system
    or the `cert:` path to the certificate in the Windows certificate store.
 
    .OUTPUTS
    System.Security.Cryptography.x509Certificates.X509Certificate2. The X509Certificate2 certificates that were found, or `$null`.
 
    .EXAMPLE
    Get-CCertificate -Path C:\Certificates\certificate.cer -Password MySuperSecurePassword
 
    Gets an X509Certificate2 object representing the certificate.cer file. Wildcards *not* supported when using a file
    system path.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint a909502dd82ae41433e6f83886b00d4277a32a7b -StoreName My -StoreLocation LocalMachine
 
    Gets an X509Certificate2 object for the certificate in the Personal store with a specific thumbprint under the Local
    Machine.
 
    .EXAMPLE
    Get-CCertificate -FriendlyName 'Development Certificate' -StoreLocation CurrentUser -StoreName TrustedPeople
 
    Gets the X509Certificate2 whose friendly name is Development Certificate from the Current User's Trusted People
    certificate store.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint $thumbprint -CustomStoreName 'SharePoint' -StoreLocation LocalMachine
 
    Demonstrates how to get a certificate from a custom store, i.e. one that is not part of the standard `StoreName`
    enumeration.
 
    .EXAMPLE
    Get-CCertificate -Path 'cert:\CurrentUser\a909502dd82ae41433e6f83886b00d4277a32a7b'
 
    Demonstrates how to get a certificate out of a Windows certificate store with its certificate path. Wildcards
    supported.
    #>

    [CmdletBinding(DefaultParameterSetName='ByPath')]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        [Parameter(Mandatory, ParameterSetName='ByPath', Position=0)]
        # The path to the certificate. Can be a file system path or a certificate path, e.g. `cert:\`. Wildcards supported.
        [String]$Path,

        [Parameter(ParameterSetName='ByPath')]
        # The password to the certificate. Must be a `[securestring]`.
        [securestring]$Password,

        [Parameter(ParameterSetName='ByPath')]
        # The storage flags to use when loading a certificate file. This controls where/how you can store the certificate in the certificate stores later. Use the `-bor` operator to combine flags.
        [Security.Cryptography.X509Certificates.X509KeyStorageFlags]$KeyStorageFlags,

        [Parameter(Mandatory, ParameterSetName='ByThumbprint')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')]
        # The certificate's thumbprint.
        [String]$Thumbprint,

        [Parameter(Mandatory, ParameterSetName='ByFriendlyName')]
        [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')]
        # The friendly name of the certificate.
        [String]$FriendlyName,

        [Parameter(Mandatory, ParameterSetName='ByFriendlyName')]
        [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprint')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')]
        # The location of the certificate's store.
        [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation,

        [Parameter(Mandatory, ParameterSetName='ByFriendlyName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprint')]
        # The name of the certificate's store.
        [Security.Cryptography.X509Certificates.StoreName]$StoreName,

        [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')]
        # The name of the non-standard, custom store.
        [String]$CustomStoreName
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    function Add-PathMember
    {
        param(
            [Parameter(Mandatory,VAlueFromPipeline=$true)]
            [Security.Cryptography.X509Certificates.X509Certificate2]
            $Certificate,

            [Parameter(Mandatory)]
            [string]
            $Path
        )

        process
        {
            $Certificate | Add-Member -MemberType NoteProperty -Name 'Path' -Value $Path -PassThru
        }
    }

    function Resolve-CertificateProviderFriendlyPath
    {
        param(
            [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
            [string]
            $PSPath,

            [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
            [Management.Automation.PSDriveInfo]
            $PSDrive
        )

        process
        {
            $qualifier = '{0}:' -f $PSDrive.Name
            $path = $PSPath | Split-Path -NoQualifier
            Join-Path -Path $qualifier -ChildPath $path
        }
    }

    if( $PSCmdlet.ParameterSetName -eq 'ByPath' )
    {
        if( -not (Test-Path -Path $Path -PathType Leaf) )
        {
            Write-Error -Message "Certificate ""$($Path)"" not found."
            return
        }

        foreach( $item in (Get-Item -Path $Path) )
        {
            Write-Debug -Message $PSCmdlet.GetUnresolvedProviderPathFromPSPath($item.PSPath)
            if( $item -is [Security.Cryptography.X509Certificates.X509Certificate2] )
            {
                $certFriendlyPath = $item | Resolve-CertificateProviderFriendlyPath
                $item | Add-PathMember -Path $certFriendlyPath | Write-Output
            }
            elseif( $item -is [IO.FileInfo] )
            {
                try
                {
                    $ctorParams = @( $item.FullName, $Password )
                    if( $KeyStorageFlags )
                    {
                        $ctorParams += $KeyStorageFlags
                    }
                    New-Object 'Security.Cryptography.X509Certificates.X509Certificate2' $ctorParams | 
                        Add-PathMember -Path $item.FullName |
                        Write-Output
                }
                catch
                {
                    $ex = $_.Exception
                    while( $ex.InnerException )
                    {
                        $ex = $ex.InnerException
                    }
                    Write-Error -Message ('Failed to create X509Certificate2 object from file ''{0}'': {1}' -f $item.FullName,$ex.Message)
                }
            }
        }
    }
    else
    {
        $storeLocationPath = '*'
        if( $StoreLocation )
        {
            $storeLocationPath = $StoreLocation
        }

        $storeNamePath = '*'
        if( $PSCmdlet.ParameterSetName -like '*CustomStoreName' )
        {
            $storeNamePath = $CustomStoreName
        }
        else
        {
            $storeNamePath = $StoreName
            if( $StoreName -eq [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority )
            {
                $storeNamePath = 'CA'
            }
        }

        if( $pscmdlet.ParameterSetName -like 'ByThumbprint*' )
        {
            $certPath = 'cert:\{0}\{1}\{2}' -f $storeLocationPath,$storeNamePath,$Thumbprint
            if( (Test-Path -Path $certPath) )
            {
                foreach( $certPathItem in (Get-ChildItem -Path $certPath) )
                {
                    $path = $certPathItem | Resolve-CertificateProviderFriendlyPath
                    $certPathItem | Add-PathMember -Path $path
                }
            }
            return
        }
        elseif( $PSCmdlet.ParameterSetName -like 'ByFriendlyName*' )
        {
            $certPath = Join-Path -Path 'cert:' -ChildPath $storeLocationPath
            $certPath = Join-Path -Path $certPath -ChildPath $storeNamePath
            $certPath = Join-Path -Path $certPath -ChildPath '*'
            return Get-ChildItem -Path $certPath |
                        Where-Object { $_.FriendlyName -eq $FriendlyName } |
                        ForEach-Object {
                            $friendlyPath = $_ | Resolve-CertificateProviderFriendlyPath
                            $_ | Add-PathMember -Path $friendlyPath
                        }
        }
        Write-Error "Unknown parameter set '$($pscmdlet.ParameterSetName)'."
    }
}




function Install-CCertificate
{
    <#
    .SYNOPSIS
    Installs an X509 certificate.
     
    .DESCRIPTION
    The `Install-CCertificate` function installs an X509 certificate. It uses the .NET X509 certificates API. The user
    performing the action must have permission to modify the store or the installation will fail. You can install from
    a file (pass the path to the file to the `-Path` parameter), or from an `X509Certificate2` object (pass it to the
    `-Certificate` parameter). Pass the store location (LocalMachine or CurrentUser) to the `-StoreLocation` parameter.
    Pass the store name (e.g. My, Root) to the `-StoreName` parameter. If the certificate has a private key and you want
    the private key exportable, use the `-Exportable` switch.
 
    If the certificate already exists in the store, nothing happens. If you want to re-install the certificate over any
    existing certificates, use the `-Force` switch.
 
    If installing a certificate from a file, and the file is password-protected, use the `-Password` parameter to pass
    the certificate's password. The password must be a `[securestring]`.
 
    This function only works on Windows.
 
    To install a certificate on a remote computer, create a remoting session with the `New-PSSession` cmdlet, and pass
    the session object to this function's `Session` parameter. When installing to a remote computer, the certificate's
    binary data is converted to a base64 encoded string and sent to the remote computer, where it is converted back
    into a certificate. If installing a certificate from a file, the file's bytes are converted to base64, sent to the
    remote computer, saved as a temporary file, installed, and the temporary file is removed.
 
    .OUTPUTS
    System.Security.Cryptography.X509Certificates.X509Certificate2. An X509Certificate2 object representing the newly installed certificate.
     
    .EXAMPLE
    Install-CCertificate -Path 'C:\Users\me\certificate.cer' -StoreLocation LocalMachine -StoreName My -Exportable -Password $securePassword
     
    Demonstrates how to install a password-protected certificate from a file and to allow its private key to be
    exportable.
     
    .EXAMPLE
    Install-CCertificate -Path C:\Users\me\certificate.cer -StoreLocation LocalMachine -StoreName My -Session $session
     
    Demonstrates how to install a certificate from a file on the local computer into the local machine's personal store
    on a remote cmoputer. You can pass multiple sessions to the `Session` parameter.
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='FromFileInWindowsStore')]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInCustomStore')]
        # The path to the certificate file.
        [String]$Path,
        
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInCustomStore')]
        # The certificate to install.
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
        
        [Parameter(Mandatory)]
        # The location of the certificate's store. To see a list of acceptable values, run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreLocation])
        [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation,
        
        [Parameter(Mandatory, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, ParameterSetName='FromCertificateInWindowsStore')]
        # The name of the certificate's store. To see a list of acceptable values run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName])
        [Security.Cryptography.X509Certificates.StoreName]$StoreName,

        [Parameter(Mandatory, ParameterSetName='FromFileInCustomStore')]
        [Parameter(Mandatory, ParameterSetName='FromCertificateInCustomStore')]
        # The name of the non-standard, custom store where the certificate should be installed.
        [String]$CustomStoreName,

        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        # Mark the private key as exportable. Only valid if loading the certificate from a file.
        [switch]$Exportable,
        
        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        # The password for the certificate. Should be a `System.Security.SecureString`.
        [securestring]$Password,

        # Use the `Session` parameter to install a certificate on remote computer(s) using PowerShell remoting. Use
        # `New-PSSession` to create a session.
        [Management.Automation.Runspaces.PSSession[]]$Session,

        # Re-install the certificate, even if it is already installed. Calls the `Add()` method for store even if the
        # certificate is in the store. This function assumes that the `Add()` method replaces existing certificates.
        [switch]$Force,

        # Return the installed certificate.
        [switch]$PassThru
    )
    
    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    if( $PSCmdlet.ParameterSetName -like 'FromFile*' )
    {   
        $resolvedPath = Resolve-Path -Path $Path
        if( -not $resolvedPath )
        {
            return
        }

        $Path = $resolvedPath.ProviderPath
        
        $fileBytes = [IO.File]::ReadAllBytes($Path)
        $encodedCert = [Convert]::ToBase64String($fileBytes)

        # Make sure loading the certificate doesn't leave temporary cruft around on the file system. We're only loading
        # the cert to get its thumbprint.
        $keyStorageFlags = @{}
        if( $StoreLocation -eq [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser )
        {
            $keyStorageFlags['KeyStorageFlags'] = 
                [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
        }
        $Certificate = Get-CCertificate -Path $Path -Password $Password @keyStorageFlags
    }
    else
    {
        $encodedCert = [Convert]::ToBase64String( $Certificate.RawData )
    }

    $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
    if( $StoreLocation -eq [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser )
    {
        $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet
    }
    $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet

    if( $Exportable )
    {
        $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
    }

    $invokeCommandArgs = @{ }
    if( $Session )
    {
        $invokeCommandArgs['Session'] = $Session
    }

    Invoke-Command @invokeCommandArgs -ScriptBlock {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory)]
            # The base64 encoded certificate to install.
            [String]$EncodedCertificate,

            # The password for the certificate.
            [securestring]$Password,

            [Parameter(Mandatory)]
            [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation,
        
            $StoreName,

            [string]$CustomStoreName,

            [Security.Cryptography.X509Certificates.X509KeyStorageFlags]$KeyStorageFlags,

            [bool]$Force,

            [bool]$WhatIf,

            [Management.Automation.ActionPreference]$Verbosity,
            
            [String]$Thumbprint
        )

        Set-StrictMode -Version 'Latest'

        $WhatIfPreference = $WhatIf
        $VerbosePreference = $Verbosity

        $certFilePath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([IO.Path]::GetRandomFileName())

        try
        {
            if( $CustomStoreName )
            {
                $store = [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $StoreLocation)
            }
            else
            {
                $StoreName = [Security.Cryptography.X509Certificates.StoreName]$StoreName
                $store = [Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
            }

            if( -not $Force )
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) )
                try
                {
                    if( $store.Certificates | Where-Object 'Thumbprint' -eq $Thumbprint )
                    {
                        return
                    }
                }
                finally
                {
                    $store.Close()
                }
            }

            $certBytes = [Convert]::FromBase64String( $EncodedCertificate )
            [IO.File]::WriteAllBytes( $certFilePath, $certBytes )

            $cert = 
                [Security.Cryptography.X509Certificates.X509Certificate2]::New($certFilePath, $Password, $KeyStorageFlags)

            $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) )

            $description = $cert.FriendlyName
            if( -not $description )
            {
                $description = $cert.Subject
            }

            $action = "install into $($StoreLocation)'s $($StoreName) store"
            $target = "$($description) ($($cert.Thumbprint))"
            if( $PSCmdlet.ShouldProcess($action, $target) )
            {
                $msg = "Installing certificate ""$($description)"" ($($cert.Thumbprint)) into $($StoreLocation)'s " +
                       "$($StoreName) store."
                Write-Verbose -Message $msg 
                $store.Add( $cert )
            }
            $store.Close()
        }
        finally
        {
            Remove-Item -Path $certFilePath -ErrorAction Ignore -WhatIf:$false -Force
        }

    } -ArgumentList $encodedCert,$Password,$StoreLocation,$StoreName,$CustomStoreName,$keyFlags,$Force,$WhatIfPreference,$VerbosePreference, $Certificate.Thumbprint

    if( $PassThru )
    {
        return $Certificate
    }
}




function Protect-CString
{
    <#
    .SYNOPSIS
    Encrypts a string.
 
    .DESCRIPTION
    The `Protect-CString` function encrypts a string using the Windows Data Protection API (DPAPI), RSA, or AES. Pass
    a plaintext string or a secure string to the `String` parameter. When encrypting a `SecureString`, it is converted
    to an array of bytes, encrypted, then the array of bytes is cleared from memory (i.e. the plaintext version of the
    `SecureString` is only in memory long enough to encrypt it). All strings and secure string bytes are re-encoded
    from UTF-16/Unicode to UTF-8 before encrypting.
 
    ## Windows Data Protection API (DPAPI)
 
    The DPAPI hides the encryptiong/decryption keys. There is a unique key for each user and a machine key. Anything
    encrypted with a user's key, can only be decrypted by that user. Anything encrypted with the machine key can be
    decrypted by anyone on that machine. Use the `ForUser` switch to encrypt with the current user's key. Use the
    `ForComputer` switch to encrypt at the machine level.
 
    If you want to encrypt something as a different user, pass that user's credentials to the `Credential` parameter.
    `Protect-CString` will launch a PowerShell process as that user to do the encryption. Encrypting as another user
    doesn't work over PowerShell Remoting.
 
    ## RSA
 
    RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. The secret is
    encrypted with the public key, and can only be decrypted with the corresponding private key. The secret being
    encrypted can't be larger than the RSA key pair's size/length, usually 1024, 2048, or 4096 bits (128, 256, and 512
    bytes, respectively). `Protect-CString` encrypts with .NET's `System.Security.Cryptography.RSACryptoServiceProvider`
    class.
 
    You can specify the public key in three ways:
 
     * by passing the `System.Security.Cryptography.X509Certificates.X509Certificate2` object to use to the
       `Certificate` parameter.
     * with a certificate in one of the Windows certificate stores. Pass its thumbprint to the `Thumbprint`
       parameter.
     * with an X509 certificate file. Pass the file's path to the `PublicKeyPath` parameter. You can also pass a
       certificate provider path to the `PublicKeyPath` parameter (e.g. `cert:`).
 
    You can generate an RSA public/private key pair with the `New-CRsaKeyPair` function.
 
    ## AES
 
    AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key/password/passphrase with
    the `Key` parameter, and that key is used to encrypt. There is no limit on the size of the data you want to encrypt.
    `Protect-CString` encrypts with the object returned by `[Security.Cryptography.Aes]::Create()`
 
    You can only pass a `[securestring]` or array of bytes as the key. The array of bytes must be 16, 24, or 32 bytes
    long. When passing a secure string, when UTF-8 encoded and converted to a byte array, it must also be 16, 24, or 32
    bytes long. You can use this code to check on the byte length of a plain text string (where $key is the plain text
    key):
 
        [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
 
    Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something.
    `Protect-CString` generates one for you. This IV must be known to decrypt the secret, so it is pre-pendeded to the
    encrypted text.
 
    This code demonstrates how to generate a key:
 
        $key = [Security.Cryptography.AesManaged]::New().Key
 
    You can save this key as a string by encoding it as a base64 string:
 
        $base64EncodedKey = [Convert]::ToBase64String($key)
 
    If you base64 encode your key's bytes, they must be converted back to bytes before passing it to `Protect-CString`.
 
        Protect-CString -String 'the secret sauce' -Key ([Convert]::FromBase64String($base64EncodedKey))
 
    .LINK
    New-CRsaKeyPair
 
    .LINK
    Unprotect-CString
 
    .LINK
    http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx
 
    .EXAMPLE
    Protect-CString -String 'TheStringIWantToEncrypt' -ForUser | Out-File MySecret.txt
 
    Encrypts the given string and saves the encrypted string into MySecret.txt. Only the user who encrypts the string
    can unencrypt it.
 
    .EXAMPLE
    Protect-CString -String $credential.Password -ForUser | Out-File MySecret.txt
 
    Demonstrates that `Protect-CString` can encrypt a `SecureString`.
 
    .EXAMPLE
    Protect-CString -String "MySuperSecretIdentity" -ForComputer
 
    Demonstrates how to encrypt a value that can only be decrypted on the current computer.
 
    .EXAMPLE
    Protect-CString -String 's0000p33333r s33333cr33333t' -Credential (Get-Credential 'builduser')
 
    Demonstrates how to use `Protect-CString` to encrypt a secret as a specific user. This is useful for situation where
    a secret needs to be encrypted by a user other than the user running `Protect-CString`. Encrypting as a specific
    user won't work over PowerShell remoting.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Certificate $myCert
 
    Demonstrates how to encrypt a secret using RSA with a `System.Security.Cryptography.X509Certificates.X509Certificate2`
    object. You're responsible for creating/loading the certificate. The `New-CRsaKeyPair` function will create a key
    pair for you, if you've got a Windows SDK installed.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to encrypt a secret using RSA with a certificate in one of the Windows certificate stores. All
    local machine and user stores are searched for the certificate with the given thumbprint that has a private key.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -PublicKeyPath 'C:\Projects\Security\publickey.cer'
 
    Demonstrates how to encrypt a secret using RSA with a certificate file. The file must be loadable by the
    `System.Security.Cryptography.X509Certificates.X509Certificate` class.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -PublicKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to encrypt a secret using RSA with a certificate in the Windows certificate store, giving its exact
    path.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j'
 
    Demonstrates how to encrypt a secret with a key, password, or passphrase. In this case, we are encrypting with a
    plaintext password.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):' -AsSecureString)
 
    Demonstrates that you can use a `SecureString` as the key, password, or passphrase.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30))
 
    Demonstrates that you can use an array of bytes as the key, password, or passphrase.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        # The string to encrypt. Any non-string object you pass will be converted to a string before encrypting by
        # calling the object's `ToString` method.
        #
        # This can also be a `SecureString` object. The `SecureString` is converted to an array of bytes, the bytes are
        # encrypted, then the plaintext bytes are cleared from memory (i.e. the plaintext password is in memory for the
        # amount of time it takes to encrypt it). Passing a secure string is the most secure usage.
        #
        # The string and secure string bytes are re-encoded as UTF-8 before encrypting.
        [Object]$String,

        [Parameter(Mandatory, ParameterSetName='DPAPICurrentUser')]
        # Encrypts for the current user so that only they can decrypt.
        [switch]$ForUser,

        [Parameter(Mandatory, ParameterSetName='DPAPILocalMachine')]
        # Encrypts for the current computer so that any user logged into the computer can decrypt.
        [switch]$ForComputer,

        [Parameter(Mandatory, ParameterSetName='DPAPIForUser')]
        # Encrypts for a specific user.
        [pscredential]$Credential,

        [Parameter(Mandatory, ParameterSetName='RsaByCertificate')]
        # The public key to use for encrypting.
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,

        [Parameter(Mandatory, ParameterSetName='RsaByThumbprint')]
        # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when encrypting. All
        # certificate stores are searched.
        [String]$Thumbprint,

        [Parameter(Mandatory, ParameterSetName='RsaByPath')]
        # The path to the public key to use for encrypting. Must be to an `X509Certificate2` object.
        [String]$PublicKeyPath,

        [Parameter(ParameterSetName='RsaByCertificate')]
        [Parameter(ParameterSetName='RsaByPath')]
        [Parameter(ParameterSetName='RsaByThumbprint')]
        # The padding mode to use when encrypting. When using an RSA public key, defaults to
        # [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1.
        [Security.Cryptography.RSAEncryptionPadding]$Padding,

        [Parameter(Mandatory, ParameterSetName='Symmetric')]
        # The key to use to encrypt the secret. Must be a `[securestring]` or an array of bytes. If passing a byte
        # array, # must be 16, 24, or 32 bytes long. If passing a secure string, when it is UTF-8 encoded and converted
        # to a byte # array, that array must also be 16, 24, or 32 bytes long. This code will tell you the length, in
        # bytes, of your plain text key (stored in the `$key`variable):
        #
        # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
        [Object]$Key
    )

    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        # We find and validate the certificate/key here so our try/catch block around actual encryption doesn't catch
        # these errors.
        [byte[]]$keyBytes = [byte[]]::New(0)
        if( $PSCmdlet.ParameterSetName -like 'Rsa*' )
        {
            if( $PSCmdlet.ParameterSetName -eq 'RsaByThumbprint' )
            {
                $Certificate = Get-Item -Path ('cert:\*\*\{0}' -f $Thumbprint) | Select-Object -First 1
                if( -not $Certificate )
                {
                    Write-Error "Certificate with thumbprint ""$($Thumbprint)"" not found."
                    return
                }
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'RsaByPath' )
            {
                $Certificate = Get-CCertificate -Path $PublicKeyPath
                if( -not $Certificate )
                {
                    return
                }
            }

            $rsaKey = $Certificate.PublicKey.Key
            if( -not $rsaKey.GetType().IsSubclassOf([Security.Cryptography.RSA]) )
            {
                $msg = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint)) is not an RSA public " +
                    "key. Found a public key of type ""$($rsaKey.GetType().FullName)"", but expected type " +
                    """$([Security.Cryptography.RSACryptoServiceProvider].FullName)""."
                Write-Error $msg
                return
            }
        }
        elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
        {
            $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Protect-CString'
            if( -not $keyBytes )
            {
                return
            }
        }


        $stringBytes = [byte[]]::New(0)
        $unicodeBytes = [Text.Encoding]::Unicode.GetBytes( $String.ToString() )
        [byte[]]$encryptedBytes = [byte[]]::New(0)
        try
        {
            if( $String -is [securestring] )
            {
                $unicodeBytes = Convert-CSecureStringToByte -SecureString $String
            }
            # Unicode takes up two bytes, so the max length of strings we can encrypt is cut from about 472 characters
            # to 236. Let's re-encode in UTF-8, which only uses one byte per character. This also maintains
            # backwards-compatability with Carbon 2.
            $stringBytes = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeBytes)
        }
        finally
        {
            $unicodeBytes.Clear()
        }

        try
        {
            if( $PSCmdlet.ParameterSetName -like 'DPAPI*' )
            {
                if( $PSCmdlet.ParameterSetName -eq 'DPAPIForUser' )
                {
                    $protectStringPath = Join-Path -Path $moduleBinRoot -ChildPath 'Protect-String.ps1' -Resolve
                    $encodedString = Protect-CString -String $String -ForComputer
                    $powershellArgs = @(
                        '-ExecutionPolicy',
                        'ByPass',
                        '-NonInteractive',
                        '-File',
                        $protectStringPath,
                        '-ProtectedString',
                        $encodedString
                    )
                    return Invoke-CPowerShell -ArgumentList $powershellArgs -Credential $Credential | Select-Object -First 1
                }
                else
                {
                    $scope = [Security.Cryptography.DataProtectionScope]::CurrentUser
                    if( $PSCmdlet.ParameterSetName -eq 'DPAPILocalMachine' )
                    {
                        $scope = [Security.Cryptography.DataProtectionScope]::LocalMachine
                    }

                    $encryptedBytes = [Security.Cryptography.ProtectedData]::Protect( $stringBytes, $null, $scope )
                }
            }
            elseif( $PSCmdlet.ParameterSetName -like 'Rsa*' )
            {

                if( -not $Padding )
                {
                    $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1
                }

                $encryptedBytes = $Certificate.PublicKey.Key.Encrypt($stringBytes, $Padding)
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
            {
                $aes = [Security.Cryptography.Aes]::Create()
                try
                {
                    $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7
                    $aes.KeySize = $keyBytes.Length * 8
                    $aes.Key = $keyBytes

                    $memoryStream = [IO.MemoryStream]::New()
                    try
                    {
                        $cryptoStream =
                            [Security.Cryptography.CryptoStream]::New(
                                $memoryStream,
                                $aes.CreateEncryptor(),
                                ([Security.Cryptography.CryptoStreamMode]::Write)
                            )

                        try
                        {
                            $cryptoStream.Write($stringBytes, 0, $stringBytes.Length)
                        }
                        finally
                        {
                            $cryptoStream.Dispose()
                        }

                        $encryptedBytes = & {
                                                $aes.IV
                                                $memoryStream.ToArray()
                                            }
                    }
                    finally
                    {
                        $memoryStream.Dispose()
                    }
                }
                finally
                {
                    $aes.Dispose()
                }
            }

            return [Convert]::ToBase64String( $encryptedBytes )
        }
        catch
        {
            Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference
        }
        finally
        {
            if( $encryptedBytes )
            {
                $encryptedBytes.Clear()
            }

            if( $stringBytes )
            {
                $stringBytes.Clear()
            }

            if( $keyBytes )
            {
                $keyBytes.Clear()
            }
        }
    }
}



function Uninstall-CCertificate
{
    <#
    .SYNOPSIS
    Removes a certificate from a certificate store.
     
    .DESCRIPTION
    The `Uninstall-CCertificate` function uses .NET's certificates API to remove a certificate from a certificate store
    for the machine or current user. Use the thumbprint to identify which certificate to remove. The thumbprint is
    unique to each certificate. The user performing the removal must have read and write permission on the store where
    the certificate is located.
 
    If the certificate isn't in the store, nothing happens, not even an error.
 
    To uninstall a certificate from a remote computer, use the `Session`parameter. You can create a new session with the
    `New-PSSession` cmdlet. You can pass multiple sessions.
 
    You can uninstall a certificate using just its thumbprint. `Uninstall-CCertificate` will search through all
    certificate locations and stores and uninstall all certificates that have the thumbprint. When you enumerate all
    certificates over a remoting session, you get a terminating `The system cannot open the device or file specified`
    error, so you can't delete a certificate with just a thumbprint over remoting.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint '570895470234023dsaaefdbcgbefa'
 
    Demonstrates how to delete a certificate from all stores it is installed in. `Uninstall-CCertificate` searches every
    certificate stores and deletes all certificates with the given thumbprint.
 
    .EXAMPLE
    '570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate
 
    Demonstrates that you can pipe a thumbprint to `Uninstall-CCertificate`. The certificate is uninstall from all
    stores it is in.
 
    .EXAMPLE
    Get-Item -Path 'cert:\LocalMachine\My\570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate
 
    Demonstrates that you can pipe a certificate `Uninstall-CCertificate`. The certificate is uninstalled from all
    stores it is in.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My
     
    Removes the 570895470234023dsaaefdbcgbefa certificate from the current user's Personal certificate store.
     
    .EXAMPLE
    Uninstall-CCertificate -Certificate $cert -StoreLocation LocalMachine -StoreName Root
     
    Demonstrates how you can remove a certificate by passing it to the `Certificate` parameter.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation LocalMachine -StoreName 'SharePoint'
 
    Demonstrates how to uninstall a certificate from a custom, non-standard store.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My -Session $session
     
    Demonstrates how to uninstall a certificate from a remote computer.
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='ByThumbprint')]
    param(
        [Parameter(Mandatory, ParameterSetName='ByThumbprint',ValueFromPipelineByPropertyName, ValueFromPipeline)]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        # The thumbprint of the certificate to remove.
        #
        # If you want to uninstall the certificate from all stores it is installed in, you can pipe the thumbprint to this parameter or you can pipe a certificate object. (This functionality was added in Carbon 2.5.0.)
        [String]$Thumbprint,
        
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        # The certificate to remove
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
        
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        # The location of the certificate's store.
        [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation,
        
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        # The name of the certificate's store.
        [Security.Cryptography.X509Certificates.StoreName]$StoreName,

        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        # The name of the non-standard, custom store where the certificate should be un-installed.
        [String]$CustomStoreName,

        [Parameter(ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndCustomStoreName')]
        # Use the `Session` parameter to uninstall a certificate on remote computer(s) using PowerShell remoting. Use
        # `New-PSSession` to create a session.
        #
        # Due to a bug in PowerShell, you can't remove a certificate by just its thumbprint over remoting. Using just a
        # thumbprint requires us to enumerate through all installed certificates. When you do this over remoting,
        # PowerShell throws a terminating `The system cannot open the device or file specified` error.
        [Management.Automation.Runspaces.PSSession[]]$Session
    )
    
    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        if( $PSCmdlet.ParameterSetName -like 'ByCertificate*' )
        {
            $Thumbprint = $Certificate.Thumbprint
        }
    
        $invokeCommandParameters = @{}
        if( $Session )
        {
            $invokeCommandParameters['Session'] = $Session
        }

        if( $PSCmdlet.ParameterSetName -eq 'ByThumbprint' )
        {
            # Must be in this order. Delete LocalMachine certs *first* so they don't show
            # up in CurrentUser stores. If you delete a certificate that "cascades" into
            # the CurrentUser store first, you'll get errors when running non-
            # interactively as SYSTEM.
            if( (Test-Path -Path 'cert:') )
            {
                Get-ChildItem -Path 'Cert:\LocalMachine','Cert:\CurrentUser' -Recurse |
                    Where-Object { -not $_.PsIsContainer } |
                    Where-Object { $_.Thumbprint -eq $Thumbprint } |
                    ForEach-Object {
                        $cert = $_
                        $description = $cert.FriendlyName
                        if( -not $description )
                        {
                            $description = $cert.Subject
                        }

                        $certPath = $_.PSPath | Split-Path -NoQualifier
                        Write-Verbose ('Uninstalling certificate ''{0}'' ({1}) at {2}.' -f $description,$cert.Thumbprint,$certPath)
                        $_
                    } |
                    Remove-Item
            }
            return
        }

        Invoke-Command @invokeCommandParameters -ScriptBlock {
            [CmdletBinding()]
            param(
                # The thumbprint of the certificate to remove.
                [String]$Thumbprint,
        
                # The location of the certificate's store.
                [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation,
        
                # The name of the certificate's store.
                $StoreName,

                # The name of the non-standard, custom store where the certificate should be un-installed.
                [String]$CustomStoreName
            )

            Set-StrictMode -Version 'Latest'

            if( $CustomStoreName )
            {
                $storeNamePath = $CustomStoreName
            }
            else
            {
                $storeNamePath = $StoreName
                if( $StoreName -eq [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority )
                {
                    $storeNamePath = 'CA'
                }
            }

            $certPath = Join-Path -Path 'Cert:\' -ChildPath $StoreLocation
            $certPath = Join-Path -Path $certPath -ChildPath $storeNamePath
            $certPath = Join-Path -Path $certPath -ChildPath $Thumbprint

            if( -not (Test-Path -Path $certPath -PathType Leaf) )
            {
                Write-Debug -Message ('Certificate {0} not found.' -f $certPath)
                return
            }

            $cert = Get-Item -Path $certPath

            if( $CustomStoreName )
            {
                $store = New-Object 'Security.Cryptography.X509Certificates.X509Store' $CustomStoreName,$StoreLocation
            }
            else
            {
                $store = New-Object 'Security.Cryptography.X509Certificates.X509Store' ([Security.Cryptography.X509Certificates.StoreName]$StoreName),$StoreLocation
            }

            $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) )

            try
            {
                $target = $cert.FriendlyName
                if( -not $target )
                {
                    $target = $cert.Subject
                }

                if( $PSCmdlet.ShouldProcess( ("certificate {0} ({1})" -f $certPath,$target), "remove" ) )
                {
                    Write-Verbose ('Uninstalling certificate ''{0}'' ({1}) at {2}.' -f $target,$cert.Thumbprint,$certPath)
                    $store.Remove( $cert )
                }
            }
            finally
            {
                $store.Close()
            }
        } -ArgumentList $Thumbprint,$StoreLocation,$StoreName,$CustomStoreName
    }
}

Set-Alias -Name 'Remove-Certificate' -Value 'Uninstall-CCertificate'




function Unprotect-CString
{
    <#
    .SYNOPSIS
    Decrypts a string.
 
    .DESCRIPTION
    `Unprotect-CString` decrypts a string encrypted via the Data Protection API (DPAPI), RSA, or AES into an array of
    bytes, which is then converted to an array of chars, which are stored in a `[securestring]`. All arrays of bytes and
    chars are cleared from memory once decryption completes.
 
    Use the `AsPlainText` switch to return a plain text string instead. When you do this, your decrypted string will
    remain in memory (and maybe disk) for an unknowable amount of time.
 
    `Unprotect-CString` can decrypt using the following techniques.
 
    ## Data Protection API
 
    The DPAPI only works on Windows. The encrypted string must have also been encrypted with the DPAPI. The string must
    have been encrypted at the current user's scope or the local machine scope.
 
    ## RSA
 
    RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. It uses a private
    key to decrypt a secret encrypted with the public key. Only the private key can decrypt secrets.
 
    You can specify the private key in these ways:
 
     * with a `[Security.Cryptography.X509Certificates.X509Certificate2]` object, via the `Certificate` parameter
     * with an X509 certificate file, via the `PrivateKeyPath` parameter. On Windows, you can use paths to items in the
       `cert:\` drive.
 
     On Windows, you can also pass the thumbprint to a certificate to the `Thumbprint` parameter, and
     `Unprotect-CString` will search the `cert:\` store for a matching certificate with a private key.
 
    ## AES
 
    AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key, password, or passphrase
    with the `Key` parameter, and that key is used to decrypt. You must decrypt with the same key you used to encrypt.
    `Unprotect-CString` uses `[Security.Cryptography.Aes]::Create()` to get an object that can do the decryption.
 
    You can only pass a `[securestring]` or byte array as the key. When passing a secure string, make sure that when
    encoded as UTF-8 and converted to a byte array, it is 16, 24, or 32 bytes long. This code will tell you how long your
    plain text password is, in UTF-8 bytes:
 
        [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
 
    Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something. If
    you encrypted the string with `Protect-CString`, one was generated for you and prepended to the encrypted string. If
    you encrypted the original string yourself, make sure the first 16 bytes of the encrypted text is the IV (since
    the encrypted bytes are base64 encoded, that means the first 24 characters of the encrypted string should be the
    IV).
 
    The help topic for `Protect-CString` demonstrates how to generate an AES key and how to encode it as a base64
    string.
 
    .LINK
    New-CRsaKeyPair
 
    .LINK
    Protect-CString
 
    .LINK
    http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $encryptedPassword
 
    Demonstrates how to decrypt a protected string which was encrypted with Microsoft's DPAPI. Windows only.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Certificate $myCert
 
    Demonstrates how to decrypt a secret using RSA with a `[Security.Cryptography.X509Certificates.X509Certificate2]`
    object. You're responsible for creating/loading it. (Carbon's `New-CRsaKeyPair` function can create public/private
    key pairs for you.)
 
    .EXAMPLE
    $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey
 
    Demonstrates that you can pipe encrypted strings to `Unprotect-CString`.
 
    .EXAMPLE
    $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey -AsSecureString
 
    Demonstrates that you can get a secure string returned to you by using the `AsSecureString` switch. This is the most
    secure way to decrypt, as the decrypted text is only in memory as arrays of bytes/chars during decryption. The
    arrays are immediately cleared after decryption. The decrypted text is never stored as a `[String]` (which remain
    in memory).
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to decrypt a secret with a certificate by passing its thumbprint to the `Thumbprint` parameter.
    `Unprotect-CString` will search the Windows certificate stores to find the certificate. All local machine and user
    stores are searched. The current user must have permission/access to the certificate's private key. Windows only.
 
    .EXAMPLE
    Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'C:\Projects\Security\publickey.cer'
 
    Demonstrates how to decrypt a secret by passing the path to an RSA private key to the `PrivateKeyPath` parameter.
    The private key file must be loadable by the `[Security.Cryptography.X509Certificates.X509Certificate]` class.
 
    .EXAMPLE
    Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to decrypt a secret using a certificate in the Windows store by passing the path to the certificate
    in PowerShell's `cert:` drive. The certificate must have a private key. Windows only.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j'
 
    Demonstrates how to decrypt a secret that was encrypted with a key, password, or passphrase. In this case, we are
    decrypting with a plaintext password.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):') -AsSecureString)
 
    Demonstrates how to decrypt a secret with a secure string that is the key, password, or passphrase. In this case,
    the user is prompted for the password securely.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30))
 
    Demonstrates that you can pass in an array of bytes as the key to the `Key` parameter. Those bytes will be used to
    decrypt the ciphertext.
    #>

    [CmdletBinding(DefaultParameterSetName='DPAPI')]
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        # The text to decrypt.
        [String]$ProtectedString,

        [Parameter(Mandatory, ParameterSetName='RSAByCertificate')]
        # The private key to use for decrypting.
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,

        [Parameter(Mandatory, ParameterSetName='RSAByThumbprint')]
        # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when decrypting. All
        # certificate stores are searched. The current user must have permission to the private key. Windows only.
        [String]$Thumbprint,

        [Parameter(Mandatory, ParameterSetName='RSAByPath')]
        # The path to the private key to use for decrypting. If given a path on the file system, the file must be
        # loadable as a `[Security.X509Certificates.X509Certificate2]` object. On Windows, you can also pass the path
        # to a certificate in PowerShell's `cert:` drive.
        [String]$PrivateKeyPath,

        [Parameter(ParameterSetName='RSAByPath')]
        # The password for the private key, if it has one. Must be a `[securestring]`.
        [securestring]$Password,

        [Parameter(ParameterSetName='RSAByCertificate')]
        [Parameter(ParameterSetName='RSAByThumbprint')]
        [Parameter(ParameterSetName='RSAByPath')]
        # The padding mode to use when decrypting. Defaults to `[Security.Cryptography.RSAEncryptionPadding]::OaepSHA1`.
        [Security.Cryptography.RSAEncryptionPadding]$Padding,

        [Parameter(Mandatory, ParameterSetName='Symmetric')]
        # The key to use to decrypt the secret. Must be a `[securestring]` or an array of bytes. The characters in the
        # secure string are converted to UTF-8 encoding before being converted into bytes. Make sure the key is the
        # correct length when UTF-8 encoded, i.e. make sure the following code returns a 16, 24, or 32 byte byte array
        # (where $key is the plain text key).
        #
        # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
        [Object]$Key,

        # Returns the decrypted value as plain text. The default is to return the decrypted value as a `[securestring]`.
        # When returned as a secure string, the decrypted bytes are only stored in memory as arrays of bytes and chars,
        # which are all cleared once the decrypted text is in the secure string. Once a secure string is converted to a
        # string, that string stays in memory (and possibly disk) for an unknowable amout of time.
        [switch]$AsPlainText
    )

    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        [byte[]]$keyBytes = [byte[]]::New(0)

        # Find and validate the RSA certificate, if needed. We do it here so our try/catch around the actual
        # decryption doesn't handle these errors.
        if( $PSCmdlet.ParameterSetName -like 'RSA*' )
        {
            if( $PSCmdlet.ParameterSetName -notlike '*ByCertificate' )
            {
                if( $PSCmdlet.ParameterSetName -like '*ByThumbprint' )
                {
                    $PrivateKeyPath = "cert:\*\*\$($Thumbprint)"
                }

                $passwordParam = @{ }
                if( $Password )
                {
                    $passwordParam = @{ Password = $Password }
                }

                $certificates = Get-CCertificate -Path $PrivateKeyPath @passwordParam
                $count = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count'
                if( $count -gt 1 )
                {
                    $msg = "Found $($count) certificates at ""$($PrivateKeyPath)"". Arbitrarily choosing the first " +
                        'one. If you get errors, consider passing the exact path to the certificate you want to ' +
                        'the "Unprotect-CString" function''s "PrivateKeyPath" parameter.'
                    Write-Warning -Message $msg
                }
                $Certificate = $certificates | Select-Object -First 1
                if( -not $Certificate )
                {
                    return
                }
            }

            $certDesc = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint))"
            if( -not $Certificate.HasPrivateKey )
            {
                $msg = "$($certDesc) doesn't have a private key. When decrypting with RSA, secrets are encrypted with " +
                    'the public key, and decrypted with a private key.'
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }

            if( -not $Certificate.PrivateKey )
            {
                $msg = "$($certDesc) has a private key, but it is null or not set. This usually means your certificate " +
                    'was imported incorrectly or was created without a private key. Make sure you''ve generated an ' +
                    'RSA public/private key pair and are using the private key. If the private key is in the Windows ' +
                    'certificate store, make sure the current user has permission to read the private key (use ' +
                    'Carbon''s `Grant-CPermission` function).'
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
        }
        elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
        {
            $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Unprotect-CString'
            if( -not $keyBytes )
            {
                return
            }
        }


        [byte[]]$decryptedBytes = [byte[]]::New(0)
        [byte[]]$encryptedBytes = [Convert]::FromBase64String($ProtectedString)
        try
        {
            if( $PSCmdlet.ParameterSetName -eq 'DPAPI' )
            {
                $decryptedBytes = [Security.Cryptography.ProtectedData]::Unprotect( $encryptedBytes, $null, 0 )
            }
            elseif( $PSCmdlet.ParameterSetName -like 'RSA*' )
            {
                [Security.Cryptography.RSA]$privateKey = $null
                $privateKeyType = $Certificate.PrivateKey.GetType()
                $isRsa = $privateKeyType.IsSubclassOf([Security.Cryptography.RSA])
                if( -not $isRsa )
                {
                    $msg = "$($certDesc) is not an RSA key. Found a private key of type " +
                           """$($privateKeyType.FullName)"", but expected type " +
                           """$([Security.Cryptography.RSA].FullName)"" or one of its sub-types."
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                    return
                }

                if( -not $Padding )
                {
                    $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1
                }

                $privateKey = $Certificate.PrivateKey
                $decryptedBytes = $privateKey.Decrypt($encryptedBytes, $padding)
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
            {
                $aes = [Security.Cryptography.Aes]::Create()
                try
                {
                    $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7
                    $aes.KeySize = $keyBytes.Length * 8
                    $aes.Key = $keyBytes
                    $iv = [byte[]]::New($aes.IV.Length)
                    [Array]::Copy($encryptedBytes, $iv, 16)

                    $encryptedBytes = $encryptedBytes[16..($encryptedBytes.Length - 1)]
                    $encryptedStream = New-Object -TypeName 'IO.MemoryStream' -ArgumentList (,$encryptedBytes)
                    try
                    {
                        $cryptoStream =
                            [Security.Cryptography.CryptoStream]::New($encryptedStream,
                                $aes.CreateDecryptor($aes.Key, $iv),
                                ([Security.Cryptography.CryptoStreamMode]::Read))
                        try
                        {
                            $streamReader = [IO.StreamReader]::New($cryptoStream)
                            try
                            {
                                [byte[]]$decryptedBytes = [Text.Encoding]::UTF8.GetBytes($streamReader.ReadToEnd())
                            }
                            finally
                            {
                                $streamReader.Dispose()
                            }
                        }
                        finally
                        {
                            $cryptoStream.Dispose()
                        }
                    }
                    finally
                    {
                        $encryptedStream.Dispose()
                    }
                }
                finally
                {
                    $aes.Dispose()
                }
            }

            $decryptedBytes = [Text.Encoding]::Convert([Text.Encoding]::UTF8, [Text.Encoding]::Unicode, $decryptedBytes)
            if( $AsPlainText )
            {
                return [Text.Encoding]::Unicode.GetString($decryptedBytes)
            }
            else
            {
                $secureString = [Security.SecureString]::New()
                [char[]]$chars = [Text.Encoding]::Unicode.GetChars( $decryptedBytes )
                for( $idx = 0; $idx -lt $chars.Count ; $idx++ )
                {
                    $secureString.AppendChar( $chars[$idx] )
                    $chars[$idx] = 0
                }

                $secureString.MakeReadOnly()
                return $secureString
            }
        }
        catch
        {
            Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference
        }
        finally
        {
            if( $decryptedBytes )
            {
                $decryptedBytes.Clear()
            }

            if( $encryptedBytes )
            {
                $encryptedBytes.Clear()
            }

            if( $keyBytes )
            {
                $keyBytes.Clear()
            }
        }
    }
}


function Use-CallerPreference
{
    <#
    .SYNOPSIS
    Sets the PowerShell preference variables in a module's function based on the callers preferences.
 
    .DESCRIPTION
    Script module functions do not automatically inherit their caller's variables, including preferences set by common
    parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't
    get passed into any function that belongs to a module.
 
    When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the
    function's caller:
 
     * ErrorAction
     * Debug
     * Confirm
     * InformationAction
     * Verbose
     * WarningAction
     * WhatIf
     
    This function should be used in a module's function to grab the caller's preference variables so the caller doesn't
    have to explicitly pass common parameters to the module function.
 
    This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d).
 
    There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that
    causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add
    explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get
    fixed.
 
    .LINK
    about_Preference_Variables
 
    .LINK
    about_CommonParameters
 
    .LINK
    https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d
 
    .LINK
    http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/
 
    .EXAMPLE
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
    Demonstrates how to set the caller's common parameter preference variables in a module function.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        #[Management.Automation.PSScriptCmdlet]
        # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]`
        # attribute.
        $Cmdlet,

        [Parameter(Mandatory)]
        # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the
        # `[CmdletBinding()]` attribute.
        #
        # Used to set variables in its callers' scope, even if that caller is in a different script module.
        [Management.Automation.SessionState]$SessionState
    )

    Set-StrictMode -Version 'Latest'

    # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken
    # from about_CommonParameters).
    $commonPreferences = @{
                              'ErrorActionPreference' = 'ErrorAction';
                              'DebugPreference' = 'Debug';
                              'ConfirmPreference' = 'Confirm';
                              'InformationPreference' = 'InformationAction';
                              'VerbosePreference' = 'Verbose';
                              'WarningPreference' = 'WarningAction';
                              'WhatIfPreference' = 'WhatIf';
                          }

    foreach( $prefName in $commonPreferences.Keys )
    {
        $parameterName = $commonPreferences[$prefName]

        # Don't do anything if the parameter was passed in.
        if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) )
        {
            continue
        }

        $variable = $Cmdlet.SessionState.PSVariable.Get($prefName)
        # Don't do anything if caller didn't use a common parameter.
        if( -not $variable )
        {
            continue
        }

        if( $SessionState -eq $ExecutionContext.SessionState )
        {
            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
        }
        else
        {
            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
        }
    }
}