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 'PSModules'

Import-Module -Name (Join-Path -Path $privateModulesRoot -ChildPath 'Carbon.Core') `
              -Function @('Invoke-CPowerShell', 'Test-COperatingSystem')

# 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-SecureStringToByte
{
    <#
    .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-SecureStringToString
{
    <#
    .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-SecureStringToByte -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-SecureStringToByte -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 Find-Certificate
{
    <#
    .SYNOPSIS
    Searches certificate stores for certificates.
 
    .DESCRIPTION
    The `Find-CCertificate` function searches through the My/Personal certificate store for the local machine and
    current user accounts for certificates that match search criteria. Use the following parameters to search:
 
    * `Subject`: return certificates with the given subject. Wildcards accepted.
    * `LiteralSubject`: return certificates whose subjects exactly match the given subject.
    * `Active`: return certificates that are active and not expired.
    * `HasPrivateKey`: return certificates that have a private key.
    * `HostName`: return certificates that authenticate the given hostname. Wildcards supported. Matches against the
      subject's common name and the certificate's subject alternate names.
    * `LiteralHostName`: return certificates that authenticate the given hostname. Matches against the subject's common
      name and the certificate's subject alternate names.
    * `KeyUsageName`: return certificates that have the given enhanced key usage, searching each usage's friendly name.
    * `KeyUsageOId`: return certificates that have the given enhanced key usage, searching each usage's object ID.
    * `Trusted`: return certificates that are trusted/verified.
 
    You can search in the local machine or current user accounts (not both) by passing the account to the
    `StoreLocation` parameter. You can search in different stores by passing the store name to the `StoreName`
    parameter.
 
    .EXAMPLE
    Find-CCertificate -Active -HostName 'dev.example.com' -KeyUsageName 'Server Authentication' -Trusted -HasPrivateKey
 
    Demonstrates how to search for a certificate using multiple criteria. In this example, we're looking for a TLS
    certificate that can be used with the `dev.example.com` hostname.
    #>

    [CmdletBinding()]
    param(
        [String] $Subject,

        [String] $LiteralSubject,

        [switch] $Active,

        [switch] $HasPrivateKey,

        [String] $HostName,

        [String] $LiteralHostName,

        [String] $KeyUsageName,

        [String] $KeyUsageOid,

        [switch] $Trusted,

        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,

        [Security.Cryptography.X509Certificates.StoreName] $StoreName =
            [Security.Cryptography.X509Certificates.StoreName]::My
    )

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

    Write-Verbose 'Find-Certificate search criteria:'
    if( $Subject )
    {
        Write-Verbose (" Subject like $($Subject)")
    }
    if( $LiteralSubject )
    {
        Write-Verbose (" Subject eq $($LiteralSubject)")
    }
    if( $Active )
    {
        Write-Verbose (' Active True')
    }
    if( $HasPrivateKey )
    {
        Write-Verbose (' HasPrivateKey True')
    }
    if( $HostName )
    {
        Write-Verbose (" HostName like $($HostName)")
    }
    if( $LiteralHostName )
    {
        Write-Verbose (" HostName eq $($LiteralHostName)")
    }
    if( $KeyUsageName )
    {
        Write-Verbose (" Key Usage $($KeyUsageName)")
    }
    if( $KeyUsageOid )
    {
        Write-Verbose (" Key Usage OID $($KeyUsageOid)")
    }
    if( $Trusted )
    {
        Write-Verbose (" Trusted True")
    }
    if( $StoreLocation )
    {
        Write-Verbose (" StoreLocation $($StoreLocation)")
    }
    if( $StoreName )
    {
        Write-Verbose (" StoreName $($StoreName)")
    }
    Write-Verbose ''

    function Test-Object 
    {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory, ValueFromPipeline)]
            [AllowEmptyString()]
            [AllowNull()]
            [Object] $InputObject,

            [Parameter(Mandatory, ParameterSetName='Equals')]
            [AllowEmptyString()]
            [AllowNull()]
            [switch] $Equals,

            [Parameter(Mandatory, ParameterSetName='LessThan')]
            [switch] $LessThan,

            [Parameter(Mandatory, ParameterSetName='GreaterThan')]
            [switch] $GreaterThan,

            [Parameter(Mandatory, ParameterSetName='Contains')]
            [switch] $Contains,

            [Parameter(Mandatory, ParameterSetName='ContainsLike')]
            [switch] $ContainsLike,

            [Parameter(Mandatory, ParameterSetName='Matches')]
            [switch] $Match,

            [Parameter(Mandatory, ParameterSetName='Like')]
            [switch] $Like,

            [Parameter(Mandatory, Position=0)]
            [Object] $Value,

            [Parameter(Mandatory)]
            [String] $Name,

            [String] $DisplayValue
        )

        process
        {
            $success = $false

            if( $Equals )
            {
                if( $null -eq $InputObject )
                {
                    if( $null -eq $Value )
                    {
                        $success = $true
                    }
                }
                elseif( $InputObject -eq $Value )
                {
                    $success = $true
                }
            }
            elseif( $LessThan )
            {
                $success = $InputObject -lt $Value
            }
            elseif( $GreaterThan )
            {
                $success = $InputObject -gt $Value
            }
            elseif( $Contains )
            {
                $success = $InputObject -contains $Value
            }
            elseif( $ContainsLike )
            {
                $success = $null -ne ($InputObject | Where-Object { $_ -like $Value })
            }
            elseif( $Match )
            {
                $success = $InputObject -match $Value
            }
            elseif( $Like )
            {
                $success = $InputObject -like $Value
            }

            $flag = '!'
            if( $success )
            {
                $flag = ' '
            }

            if( -not $DisplayValue )
            {
                $displayValues =
                    $InputObject |
                    ForEach-Object { $_ } |
                    ForEach-Object {
                        if( $_ -is [DateTime] )
                        {
                            return $_.ToString('yyyy-MM-dd HH:mm:ss')
                        }
                        return $_.ToString()
                    }
                $DisplayValue = $displayValues -join ', '
            }

            $name = '{0,-22}' -f $Name
            $msg = " $($flag) $($Name) $($DisplayValue)"
            if( $longestLineLength -lt $msg.Length )
            {
                $script:longestLineLength = $msg.Length
            }
            Write-Verbose -Message $msg
            return $success
        }
    }

    $getCertArgs = @{}

    if( $StoreLocation )
    {
        $getCertArgs['StoreLocation'] = $StoreLocation
    }

    $certs = Get-Certificate @getCertArgs -StoreName $StoreName
    $isFirstCert = $true
    foreach( $certificate in $certs )
    {
        if( $isFirstCert )
        {
            $isFirstCert = $false
        }
        else
        {
            Write-Verbose ('')
        }

        Write-Verbose -Message ("$($certificate.Subject)")
        Write-Verbose -Message ("$($certificate.Thumbprint)")

        $script:longestLineLength = $certificate.Subject.Length
        if( $script:longestLineLength -lt $certificate.Thumbprint.Length )
        {
            $script:longestLineLength = $certificate.Thumbprint.Length
        }

        if( $Subject )
        {
            if( -not ($certificate.Subject | Test-Object -Like $Subject -Name 'subject') )
            {
                continue
            }
        }

        if( $LiteralSubject )
        {
            if( -not ($certificate.Subject | Test-Object -Equals $LiteralSubject -Name 'subject') )
            {
                continue
            }
        }

        if( $HasPrivateKey.IsPresent )
        {
            if( -not ($certificate.HasPrivateKey | Test-Object -Equals $HasPrivateKey -Name 'private key') )
            {
                continue
            }
        }

        if( $Active )
        {
            if( -not ($certificate.NotBefore | Test-Object -LessThan (Get-Date) -Name 'start date') )
            {
                continue
            }

            if( -not ($certificate.NotAfter | Test-Object -GreaterThan (Get-Date) -Name 'expiration date') )
            {
                continue
            }
        }

        $subjectHostName = ''
        if( $certificate.Subject -match '^CN=([^,]+),?.*$' )
        {
            $subjectHostName = $Matches[1]
        }

        if( $HostName )
        {
            $inSubject = $subjectHostName | Test-Object -Like $HostName -Name 'subject common name'
            if( -not $inSubject )
            {
                $found =
                    (,$certificate.DnsNameList | Test-Object -ContainsLike $HostName -Name 'subject alternate name')
                if( -not $found )
                {
                    continue
                }
            }
        }

        if( $LiteralHostName )
        {
            $inSubject = $subjectHostName | Test-Object -Equals $LiteralHostName -Name 'subject common name'
            if( -not $inSubject )
            {
                $found =
                    (,$certificate.DnsNameList | Test-Object -Contains $LiteralHostName -Name 'subject alternate name')
                if( -not $found )
                {
                    continue
                }
            }
        }

        if( $KeyUsageName -or $KeyUsageOid )
        {
            if( $certificate.EnhancedKeyUsageList.Count -eq 0 )
            {
                $certificate.EnhancedKeyUsageList.Count |
                    Test-Object -Equals 0 -Name 'key usage' -DisplayValue 'Any' |
                    Out-Null
            }
            else
            {
                if( $KeyUsageName )
                {
                    $names = $certificate.EnhancedKeyUsageList | Select-Object -ExpandProperty 'FriendlyName'
                    if( -not (,$names | Test-Object -Contains $KeyUsageName -Name 'key usage') )
                    {
                        continue
                    }
                }

                if( $KeyUsageOid )
                {
                    $oids = $certificate.EnhancedKeyUsageList | Select-Object -ExpandProperty 'ObjectId'
                    if( -not (,$oids | Test-Object -Contains $KeyUsageOid -Name 'key usage') )
                    {
                        continue
                    }
                }
            }
        }

        if( $Trusted )
        {
            if( -not $certificate.Verify() | Test-Object -Equals $true -Name 'trusted' )
            {
                continue
            }
        }
        
        Write-Verbose -Message "^$('-' * ($longestLineLength - 1))^"
        $certificate | Write-Output
    }
}


function Find-TlsCertificate
{
    <#
    .SYNOPSIS
    Finds a TLS certificate that matches a hostname from the certificate stores.
 
    .DESCRIPTION
    The `Find-CTlsCertficate` function finds a TLS certificate for the current computer. It determines the computer's
    domain name/hostname using the `HostName` and `DomainName` properties from
    `[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()`. To get a certificate for a custom
    hostname, pass that hostname to the `HostName` parameter.
 
    The `Find-CTlsCertificate` function returns the first certificate that:
 
    * has a private key.
    * hasn't expired and whose start date is in the past
    * contains the `HostName` in its subject or Subject Alternative Name list.
    * has 'Server Authentication' in its enhanced key usage list or has no enhanced key usage metadata.
 
    Additionally, you can use the `-Trusted` switch to only return trusted certificates, i.e. certificates whose
    issuing certificate authorities in its cert chain are installed in the local machine or current user's [trusted
    certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
    `Find-CTlsCertificate` calls the `Verify()` method on each `X509Certificate2` object to determine if that
    certificate is trusted.
 
    If multiple certificates are found, `Find-CTlsCertificate` will return the certificate that expires later. If no
    certificate is found, it writes an error and returns nothing.
 
    Use the `-Verbose` switch to see why a certificate is or isn't being found and selected by `Find-CTlsCertificate`.
    You'll see messages for each selection criteria and if a criterium isn't met, you'll see a `!` flag. For example,
    this verbose output from `Find-CTlsCertificate -HostName 'example.com' -Trusted -Verbose`
 
        VERBOSE: FCD157FCB753E2B388183C19021301B1739DF1E2
        VERBOSE: CN=sub.example.com
        VERBOSE: private key True
        VERBOSE: start date 2021-10-18 15:43:23
        VERBOSE: expiration date 2023-10-19 15:43:23
        VERBOSE: ! hostname ['sub.example.com']
        VERBOSE:
        VERBOSE: 7F660D4F7201B8EB8F7F6AC2A0906253C240584F
        VERBOSE: CN=example.com
        VERBOSE: private key True
        VERBOSE: start date 2021-10-18 15:43:23
        VERBOSE: expiration date 2022-10-19 15:43:23
        VERBOSE: hostname ['example.com']
        VERBOSE: key usage Any
        VERBOSE: trusted True
        VERBOSE: ^--------------------------------------^
 
    shows that certificate `FCD157FCB753E2B388183C19021301B1739DF1E2` wasn't selected because its hostname didn't match
    the `example.com` hostname, but that certificate `7F660D4F7201B8EB8F7F6AC2A0906253C240584F` was selected because
    it matched all six criteria.
 
    .OUTPUTS
    System.Security.Cryptography.x509Certificates.X509Certificate2 that was found or `$null` if no match was found.
 
    .EXAMPLE
    Find-CTlsCertificate
 
    Demonstrates how to find a TLS certificate for the current computer using the computer's hostname and domain name
    as determined by the `[System.Net.NetworkInformation.IPGlobalProperties]` object returned by the
    ``[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()::GetIPGlobalProperties()` method.
 
    .EXAMPLE
    Find-CTlsCertificate -HostName 'example.com'
 
    Demonstrates how to find a valid TLS valid certificate for a hostname, in this example, `example.com`.
 
    .EXAMPLE
    Find-CTlsCertificate -HostName 'example.com' -Trusted
 
    Demonstrates how to find a valid *trusted* TLS certificate by using the `-Trusted` switch. Trusted certificates
    are issued by certificate authorities whose certificates (and all certificates in the certificate chain) are in the
    local machine or current user's [trusted certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
    #>

    [CmdletBinding()]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        # The hostname whose TLS certificate to find.
        [String] $HostName,

        # In addition to all other search criteria, if set, causes `Find-CTLSCertificate` to only return trusted
        # certificates, i.e. certificates that are issued by a certificate authority installed in the local machine or
        # current user's [trusted certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
        # `Find-CTlsCertificate` calls the `Verify()` method on each certificate to determine if a certificate is
        # trusted.
        [switch] $Trusted
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState
    
    if( -not $HostName )
    {
        $ipProperties = [Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
        $HostName= "$($ipProperties.HostName).$($ipProperties.DomainName)"
    }

    $certificate =
        Find-Certificate -HostName $HostName `
                         -Active `
                         -HasPrivateKey `
                         -KeyUsageName 'Server Authentication' `
                         -Trusted:$Trusted |
        Sort-Object -Property 'NotAfter' -Descending |
        Select-Object -First 1
    
    if( $certificate )
    {
        return $certificate
    }

    $isTrustedMsg = ''
    if( $Trusted )
    {
        $isTrustedMsg = '* is trusted.' + [Environment]::NewLine
    }
    $msg = "TLS certificate for $($HostName) does not exist. Make sure there is a certificate in the My certificate " +
           'store for the LocalMachine or CurrentUser that:' + [Environment]::NewLine +
           ' ' + [Environment]::NewLine +
           '* has a private key' + [Environment]::NewLine +
           '* hasn''t expired and whose "NotBefore"/"Valid From" date is in the past' + [Environment]::NewLine +
           "* has subject ""CN=$($HostName)""; or whose Server Alternative Name contains ""$($HostName)""" +
           [Environment]::NewLine +
           '* has an enhanced key usage of "Server Authentication" (or no enhanced key usage ' +
           'metadata) ' + [Environment]::NewLine +
           $isTrustedMsg +
           ' ' + [Environment]::NewLine + 
           'Use the -Verbose switch to see why each certificate was rejected.'

    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
}


function Get-Certificate
{
    <#
    .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.
 
    On Windows, the path can also be a path to a certificate in PowerShell's certificate drive (i.e. the path begins
    with `cert:\`). When getting a path in the `cert:` drive, the `Password` and `KeyStorageFlags` parameters are
    ignored. The certificate is returned. Wildcards allowed.
 
    When called with no parameters, `Get-CCertificate` returns all certificates in all certificate locations and stores
    (except stores with custom names). You can filter what certificates to return using any combination of these
    parameters. A certificate must match all filters to be returned.
 
    * `StoreLocation`: only return certificates in one of the store locations, `CurrentUser` or `LocalMachine`.
    * `StoreName`: only return certificates from this store. Can't be used with `CustomStoreName`.
    * `CustomStoreName`: only return certificates from this custom store name. Can't be used with `StoreName`.
    * `Subject`: only return certificates with this subject. Wildcards allowed.
    * `LiteralSubject`: only return certificates with this exact subject.
    * `Thumbprint`: only return certificates with this thumbprint. Wildcards allowed.
    * `FriendlyName`: only return certificates with this friendly name. Wildcards allowed. Friendly names are
      Windows-only. If you pass a friendly name on other platforms, you'll get no certificates back.
    * `LiteralFriendlyName`: only return certificates with this exact friendly name. Friendly names are Windows-only. If
      you pass a friendly name on other platforms, you'll get no certificates back.
 
    `Get-CCertificate` adds a `Path` property to the returned objects that is the file system path where the certificate
    was loaded from, or, if loaded from a Windows certificate store, the path to the certificate in the `cert:` drive.
 
    When loading certificates from a certificate store, `Get-CCertificate` adds `StoreLocation` and `StoreName`
    properties for the store where the certificate was found.
 
    .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.
 
    .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
 
    Demonstrates how to get all certificates in all current user and local machine stores.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint a909502dd82ae41433e6f83886b00d4277a32a7b
 
    Demonstrates how to find certificates with a given thumbprints.
 
    .EXAMPLE
    Get-CCertificate -StoreLocation CurrentUser
 
    Demonstrates how to get all certificates for a specific location.
 
    .EXAMPLE
    Get-CCertificate -StoreName My
 
    Demonstrates how to get all certificates from a specific store.
 
    .EXAMPLE
    Get-CCertificate -Subject 'CN=Carbon.Cryptography'
 
    Demonstrates how to find all certificates in all stores that have a specific subject.
 
    .EXAMPLE
    Get-CCertificate -LiteralSubject 'CN=*.example.com'
 
    Demonstrates how to find a certificate that has wildcards in its subject using the `LiteralSubject` parameter.
 
    .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 -FriendlyName 'My Friendly Name'
 
    Demonstrates how to get all certificates with a specific friendly name. Friendly names are Windows-only. No
    certificates will be returned when using this parameter on non-Windows platforms.
 
    .EXAMPLE
    Get-CCertificate -LiteralFriendlyName '*My Friendly Name'
 
    Demonstrates how to find a certificate that has wildcards in its subject using the `LiteralFriendlyName` parameter.
 
    .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. The `cert:` drive only exists on Windows. If you use a `cert:` path on non-Windows platforms, you'll get
    an error.
    #>

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

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

        # 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.
        [Parameter(ParameterSetName='ByPath')]
        [Security.Cryptography.X509Certificates.X509KeyStorageFlags] $KeyStorageFlags,

        # The certificate's thumbprint. Wildcards allowed.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $Thumbprint,

        # The subject of the certificate. Wildcards allowed.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $Subject,

        # The literal subject of the certificate.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $LiteralSubject,

        # The friendly name of the certificate. Wildcards allowed. Friendly name is Windows-only. If you search by
        # friendly name on other platforms, you'll never get any certificates back.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $FriendlyName,

        # The literal friendly name of the certificate. Friendly name is Windows-only. If you search by friendly name on
        # other platforms, you'll never get any certificates back.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $LiteralFriendlyName,

        # The location of the certificate's store.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,

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

        # The name of the non-standard, custom store.
        [Parameter(Mandatory, ParameterSetName='FromCertificateStoreCustomStore')]
        [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." -ErrorAction $ErrorActionPreference
            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( $PSBoundParameters.ContainsKey('KeyStorageFlags') )
                    {
                        # macOS doesn't allow ephemeral key storage, which is kind of weird but whatever.
                        if( (Test-COperatingSystem -MacOS) )
                        {
                            $KeyStorageFlags = 
                                $KeyStorageFlags -band -bnot [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
                        }
                        $ctorParams += $KeyStorageFlags
                    }
                    New-Object 'Security.Cryptography.X509Certificates.X509Certificate2' -ArgumentList $ctorParams | 
                        Add-PathMember -Path $item.FullName |
                        Write-Output
                }
                catch
                {
                    $ex = $_.Exception
                    while( $ex.InnerException )
                    {
                        $ex = $ex.InnerException
                    }
                    $msg = "[$($ex.GetType().FullName)] exception creating X509Certificate2 object from file " +
                           """$($item.FullName)"": $($ex)"
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                }
            }
        }
        return
    }

    $foundCerts = @{}
    Write-Debug -Message "[$($MyInvocation.MyCommand.Name)]"
    $locationWildcard = '*'
    if( $StoreLocation )
    {
        $locationWildcard = $StoreLocation.ToString()
    }

    $storeNameWildcard = '*'
    if( $StoreName )
    {
        $storeNameWildcard = $StoreName.ToString()
    }
    Write-Debug -Message " $($locationWildcard)\$($storeNameWildcard)"

    # If we're searching for a certificate, don't write an error if one isn't found. Only write an error if the user
    # is looking for a specific certificate in a specific location and store.
    $searching = [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Thumbprint) -or `
                 [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($FriendlyName) -or `
                 [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Subject) -or `
                 $locationWildcard -eq '*' -or `
                 ($storeNameWildcard -eq '*' -and -not $CustomStoreName)
                 
    [Security.Cryptography.X509Certificates.StoreLocation] $currentUserLocation =
        [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
    [Security.Cryptography.X509Certificates.StoreLocation] $localMachineLocation =
        [Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine

    $result = @()
    @($currentUserLocation, $localMachineLocation) |
        Where-Object { $_.ToString() -like $locationWildcard } |
        ForEach-Object {
            $location = $_
            Write-Debug -Message " $($location)"

            if( $CustomStoreName )
            {
                try
                {
                    Write-Debug -Message " $($CustomStoreName)"
                    [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $location) |
                        Write-Output
                }
                catch
                {
                    $msg = "Failed to open ""$($location)\$($CustomStoreName)"" custom store: $($_)"
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                }
                return
            }

            Write-Debug -Message " $($storeNameWildcard)"

            [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName]) |
                Where-Object { $_.ToString() -like $storeNameWildcard } |
                ForEach-Object {
                    $name = $_
                    try
                    {
                        [Security.Cryptography.X509Certificates.X509Store]::New($name, $location) |
                            Write-Output
                    }
                    catch
                    {
                        $ex = $_.Exception
                        while( $ex.InnerException )
                        {
                            $ex = $ex.InnerException
                        }
                        $msg = "Exception opening ""$($location)\$($name)"" store: " +
                               "[$($ex.GetType().FullName)]: $($ex)"
                        Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                    }
                }
        } |
        Foreach-Object {
            $openFlags = [Security.Cryptography.X509Certificates.OpenFlags]::OpenExistingOnly -bor `
                         [Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly

            [Security.Cryptography.X509Certificates.X509Store] $store = $_
            try
            {
                $store.Open($openFlags)
                $storeNamePropValue = $store.Name
                if( -not $CustomStoreName )
                {
                    if( $storeNamePropValue -eq 'CA' )
                    {
                        $storeNamePropValue = [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority
                    }
                    else
                    {
                        $storeNamePropValue = [Security.Cryptography.X509Certificates.StoreName]$storeNamePropValue
                    }
                }
                Write-Debug " $($store.Location) $($store.Name)"
                $store.Certificates |
                    Add-Member -MemberType NoteProperty -Name 'StoreLocation' -Value $store.Location -PassThru |
                    Add-Member -MemberType NoteProperty -Name 'StoreName' -Value $storeNamePropValue -PassThru |
                    Add-Member -MemberType ScriptProperty -Name 'Path' -Value {
                        if( -not (Test-Path -Path 'cert:') )
                        {
                            return
                        }

                        $storeNamePath = $this.StoreName
                        if( $storeNamePath.ToString() -eq 'CertificateAuthority' )
                        {
                            $storeNamePath = 'CA'
                        }

                        $path = Join-Path -Path 'cert:' -ChildPath $this.StoreLocation
                        $path = Join-Path -Path $path -ChildPath $storeNamePath
                        $path = Join-Path -Path $path -ChildPath $this.Thumbprint
                        return $path
                    } -PassThru
            }
            # Store doesn't exist.
            catch [Security.Cryptography.CryptographicException]
            {
                $Global:Error.RemoveAt(0)
            }
            catch
            {
                $ex = $_.Exception
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception opening and iterating certificates in " +
                       """$($store.Location)\$($store.Name)"" store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            }
            finally
            {
                $store.Dispose()
            }
        } |
        Where-Object {
            $key = "$($_.StoreLocation)\$($_.StoreName)\$($_.Thumbprint)"
            if( $foundCerts.ContainsKey($key) )
            {
                return $false
            }
            $foundCerts[$key] = $_
            return $true
        } |
        Where-Object {
            if( -not $Subject )
            {
                return $true
            }
            return $_.Subject -like $Subject
        } |
        Where-Object {
            if( -not $LiteralSubject )
            {
                return $true
            }

            return $_.Subject -eq $LiteralSubject
        } |
        Where-Object {
            if( -not $Thumbprint )
            {
                return $true
            }
            return $_.Thumbprint -like $Thumbprint
        } |
        Where-Object {
            if( -not $FriendlyName )
            {
                return $true
            }
            return $_.FriendlyName -like $FriendlyName
        } |
        Where-Object {
            if( -not $LiteralFriendlyName )
            {
                return $true
            }
            return $_.FriendlyName -eq $LiteralFriendlyName
        } |
        ForEach-Object { $_.pstypenames.Insert(0, 'Carbon.Cryptography.X509Certificate2') ; $_ } |
        Tee-Object -Variable 'result' |
        Write-Output

    if( -not $searching -and -not $result )
    {
        $fields = [Collections.ArrayList]::New()
        if( $Subject )
        {
            $field = "Subject like ""$($Subject)"""
            [void]$fields.Add($field)
        }

        if( $LiteralSubject )
        {
            $field = "Subject equal ""$($LiteralSubject)"""
            [void]$fields.Add($field)
        }

        if( $Thumbprint )
        {
            $field = "Thumbprint like ""$($Thumbprint)"""
            [void]$fields.Add($field)
        }

        if( $FriendlyName )
        {
            $field = "Friendly Name like ""$($FriendlyName)"""
            [void]$fields.Add($field)
        }

        if( $LiteralFriendlyName )
        {
            $field = "Friendly Name equal ""$($LiteralFriendlyName)"""
            [void]$fields.Add($field)
        }

        if( $StoreName )
        {
            $storeDisplayName = $StoreName.ToString()
        }
        elseif( $CustomStoreName )
        {
            $storeDisplayName = "$($CustomStoreName) custom"
        }

        $lastField = ''
        if( $fields.Count -gt 1 )
        {
            $lastField = ", and $($fields[-1])"
            $fields = $fields[0..($fields.Count - 2)]
        }

        $msg = "Certificate with $($fields -join ', ')$($lastField) does not exist in the $($StoreLocation)\" +
               "$($storeDisplayName) store."
        Write-Error -Message $msg -ErrorAction $ErrorActionPreference
    }
}




function Install-Certificate
{
    <#
    .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(
        # The path to the certificate file.
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInCustomStore')]
        [String] $Path,
        
        # The certificate to install.
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInCustomStore')]
        [Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
        
        # The location of the certificate's store. To see a list of acceptable values, run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreLocation])
        [Parameter(Mandatory)]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
        # The name of the certificate's store. To see a list of acceptable values run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName])
        [Parameter(Mandatory, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, ParameterSetName='FromCertificateInWindowsStore')]
        [Security.Cryptography.X509Certificates.StoreName] $StoreName,

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

        # Mark the private key as exportable. Only valid if loading the certificate from a file.
        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        [switch] $Exportable,
        
        # The password for the certificate. Should be a `System.Security.SecureString`.
        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        [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

    $ephemeralKeyFlag = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
    $defaultKeyFlag = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet

    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)
        $keyFlags = $ephemeralKeyFlag
        if( (Test-COperatingSystem -MacOS) )
        {
            $keyFlags = $defaultKeyFlag
        }

        # We need the certificate thumbprint so we can check if the certificate exists or not.
        $Certificate = [Security.Cryptography.X509Certificates.X509Certificate]::New($Path, $Password, $keyFlags)
        try
        {
            $thumbprint = $Certificate.Thumbprint
        }
        finally
        {
            $Certificate.Reset()
        }
        $Certificate = $null
    }
    else
    {
        $thumbprint = $Certificate.Thumbprint
        $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(
            # The base64 encoded certificate to install.
            [Parameter(Mandatory)]
            [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())

        [Security.Cryptography.X509Certificates.X509Certificate2] $cert = $null
        [Security.Cryptography.X509Certificates.X509Store] $store = $null
        if( $CustomStoreName )
        {
            $storeNameDisplay = $CustomStoreName
            $store = [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $StoreLocation)
        }
        else
        {
            $StoreName = [Security.Cryptography.X509Certificates.StoreName]$StoreName
            $storeNameDisplay = $StoreName.ToString()
            $store = [Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
        }

        if( -not $Force )
        {
            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) )
                if( $store.Certificates | Where-Object 'Thumbprint' -eq $Thumbprint )
                {
                    return
                }
            }
            catch
            {
                $msg = "Exception reading certificates from $($StoreLocation)\$($storeNameDisplay) store: $($_)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }
        }

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

        # Make sure the key isn't persisted if we're not going to store it.
        if( $WhatIf )
        {
            # We don't use EphemeralKeySet because it isn't supported on macOS.
            $KeyStorageFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet
        }

        try
        {
            $cert = 
                [Security.Cryptography.X509Certificates.X509Certificate2]::New($certFilePath, $Password, $KeyStorageFlags)
        }
        catch
        {
            $msg = "Exception reading certificate from file: $($_)"
            Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            return
        }
        
        $description = $cert.FriendlyName
        if( -not $description )
        {
            $description = $cert.Subject
        }

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

            $action = "install into $($StoreLocation)\$($storeNameDisplay) store"
            $target = "$($description) ($($cert.Thumbprint))"
            if( $PSCmdlet.ShouldProcess($target, $action) )
            {
                $msg = "Installing certificate ""$($description)"" ($($cert.Thumbprint)) into $($StoreLocation)\" +
                    "$($storeNameDisplay) store."
                Write-Verbose -Message $msg 
                $store.Add( $cert )
            }
        }
        catch
        {
            if( (Test-COperatingSystem -MacOS) -and ($cert.HasPrivateKey -and -not $Exportable) )
            {
                $msg = "Exception installing certificate ""$($description)"" ($($cert.Thumbprint)) into " +
                       "$($StoreLocation)\$($storeNameDisplay): $($_). On macOS, certificates with private keys " +
                       "must be exportable. Update $($MyInvocation.MyCommand.Name) with the ""-Exportable"" switch."
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }

            $msg = "Exception installing certificate in $($StoreLocation)\$($storeNameDisplay) store: $($_)"
            Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            return
        }
        finally
        {
            Remove-Item -Path $certFilePath -ErrorAction Ignore -WhatIf:$false -Force

            if( $cert )
            {
                $cert.Reset()
            }

            if( $store )
            {
                $store.Close()
            }
        }
    } -ArgumentList $encodedCert,
                    $Password,
                    $StoreLocation,
                    $StoreName,
                    $CustomStoreName,
                    $keyFlags,
                    $Force,
                    $WhatIfPreference,
                    $VerbosePreference,
                    $thumbprint

    if( $PassThru )
    {
        # Don't return a certificate object created by this function. It may have been loaded from a file and stored
        # in a temp file on disk. If that certificate object isn't properly disposed, the temp file can stick around
        # slowly filling up disks.
        $storeParam = @{ StoreName = $StoreName }
        if( $CustomStoreName )
        {
            $storeParam = @{ CustomStoreName = $CustomStoreName }
        }
        return Get-Certificate -Thumbprint $thumbprint -StoreLocation $StoreLocation @storeParam
    }
}




function Protect-String
{
    <#
    .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-Certificate -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-SecureStringToByte -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-String -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-Certificate
{
    <#
    .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(
        # 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.)
        [Parameter(Mandatory, ParameterSetName='ByThumbprint', ValueFromPipelineByPropertyName, ValueFromPipeline)]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [String] $Thumbprint,
        
        # The certificate to remove
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
        
        # The location of the certificate's store.
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
        # The name of the certificate's store.
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Security.Cryptography.X509Certificates.StoreName] $StoreName,

        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [String] $CustomStoreName,

        # 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.
        [Parameter(ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndCustomStoreName')]
        [Management.Automation.Runspaces.PSSession[]] $Session
    )
    
    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        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.
            $certsToDelete = & {
                Get-Certificate -StoreLocation LocalMachine -Thumbprint $Thumbprint
                Get-Certificate -StoreLocation CurrentUser -Thumbprint $Thumbprint
            }
            foreach( $certToDelete in $certsToDelete )
            {
                Uninstall-Certificate -Thumbprint $Thumbprint `
                                      -StoreLocation $certToDelete.StoreLocation `
                                      -StoreName $certToDelete.StoreName
            }
            return
        }

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

        if( $CustomStoreName )
        {
            # This is just so we can pass a value to the Invoke-Command script block. The store name enum doesn't have a
            # "not set" value so when it is "$null", the call to Invoke-Command fails.
            $StoreName = [Security.Cryptography.X509Certificates.StoreName]::My
        }

        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.
                [Security.Cryptography.X509Certificates.StoreName] $StoreName,

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

            Set-StrictMode -Version 'Latest'

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

            $certToRemove = $null
            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) )
                $certToRemove = $store.Certificates | Where-Object { $_.Thumbprint -eq $Thumbprint }
                if( -not $certToRemove )
                {
                    return
                }
            }
            catch
            {
                $ex = $_.Exception.InnerException
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception reading certificates from $($StoreLocation)\" +
                       "$($storeNameDisplay) store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }

            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) )
                $target = $certToRemove.FriendlyName
                if( -not $target )
                {
                    $target = $certToRemove.Subject
                }

                $shouldProcessTarget = "$($target) in $($StoreLocation)\$($storeNameDisplay)"
                if( $PSCmdlet.ShouldProcess($shouldProcessTarget, 'remove') )
                {
                    $msg = "Uninstalling certificate ""$($target)"" ($($Thumbprint)) from $($StoreLocation)\" +
                           "$($storeNameDisplay) store."
                    Write-Verbose $msg
                    $certToRemove | ForEach-Object { $store.Remove($_) }
                }
            }
            catch
            {
                $ex = $_.Exception.InnerException
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception uninstalling certificate in $($StoreLocation)\" +
                       "$($storeNameDisplay) store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }
        } -ArgumentList $Thumbprint,$StoreLocation,$StoreName,$CustomStoreName
    }
}



function Unprotect-String
{
    <#
    .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-Certificate -Path $PrivateKeyPath @passwordParam
                $count = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count'
                if( $count -gt 1 )
                {
                    $certificates = $certificates | Where-Object { $_.HasPrivateKey -and $_.PrivateKey }
                    $privateKeyCount = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count'

                    if( $privateKeyCount -gt 1 )
                    {
                        $msg = "Found $($privateKeyCount) certificates (which contain private keys) 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
                    }
                    elseif( $privateKeyCount -eq 0 )
                    {

                        $installedInCertStoreMsg = ''
                        if ($PSCmdlet.ParameterSetName -eq 'RSAByThumbprint')
                        {
                            $installedInCertStoreMsg =
                                'This is usually because the certificate was installed without a private key or the ' +
                                'current user doesn''t have permission to read the private key.'
                        }

                        "Found $($count) certificates at ""$($PrivateKeyPath)"" but none of them contain a private " +
                        "key or the private key is null.$(' ' + $installedInCertStoreMsg)" | Write-Error
                        return
                    }
                }
                $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)
        }
    }
}