Skip to content

Instantly share code, notes, and snippets.

@martin77s
Last active February 15, 2018 08:34
Show Gist options
  • Save martin77s/3ccff3848f943fa5d97a0799faafba69 to your computer and use it in GitHub Desktop.
Save martin77s/3ccff3848f943fa5d97a0799faafba69 to your computer and use it in GitHub Desktop.
Get the certificate selected in Get-Credential
function Get-CertificateFromCredential {
param([PSCredential]$Credential)
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class NativeMethods {
public enum CRED_MARSHAL_TYPE {
CertCredential = 1,
UsernameTargetCredential
}
[StructLayout(LayoutKind.Sequential)]
public struct CERT_CREDENTIAL_INFO {
public uint cbSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] rgbHashOfCert;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CredUnmarshalCredential(
IntPtr MarshaledCredential,
out CRED_MARSHAL_TYPE CredType,
out IntPtr Credential
);
}
'@ -ReferencedAssemblies System.Runtime.InteropServices
$credData = [IntPtr]::Zero
$credInfo = [IntPtr]::Zero
$credType = [NativeMethods+CRED_MARSHAL_TYPE]::CertCredential
try {
$credData = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($Credential.UserName);
$success = [NativeMethods]::CredUnmarshalCredential($credData, [ref] $credType, [ref] $credInfo)
if ($success) {
[NativeMethods+CERT_CREDENTIAL_INFO] $certStruct = [NativeMethods+CERT_CREDENTIAL_INFO][System.Runtime.InteropServices.Marshal]::PtrToStructure(
$credInfo, [System.Type][NativeMethods+CERT_CREDENTIAL_INFO])
[byte[]] $rgbHash = $certStruct.rgbHashOfCert
[string] $hex = [BitConverter]::ToString($rgbHash) -replace '-'
$certCredential = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store -ArgumentList @(
[System.Security.Cryptography.X509Certificates.StoreName]::My,
[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
$certsReturned = $store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $hex, $false)
if($null -eq $certsReturned) {
throw ('Could not find a certificate with thumbprint {0}' -f $hex)
}
$certsReturned[0]
}
} catch {
throw ('An error occured: {0}' -f $_.Exception.Message)
}
finally {
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($credData)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($credInfo)
if($null -ne $store) { $store.Close() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment