PowerShell Get Thumbprint Certificate with Password PFX File

I am trying to get the fingerprint of a password protected pfx file with this code:

function Get-CertificateThumbprint {
    # 
    # This will return a certificate thumbprint, null if the file isn't found or throw an exception.
    #

    param (
        [parameter(Mandatory = $true)][string] $CertificatePath,
        [parameter(Mandatory = $false)][string] $CertificatePassword
    )

    try {
        if (!(Test-Path $CertificatePath)) {
            return $null;
        }

        if ($CertificatePassword) {
            $sSecStrPassword = ConvertTo-SecureString -String $CertificatePassword -Force –AsPlainText
        }

        $certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        $certificateObject.Import($CertificatePath, $sSecStrPassword);

        return $certificateObject.Thumbprint
    } catch [Exception] {
        # 
        # Catch accounts already added.
        throw $_;
    }
}

When I run it, I get this error:

Cannot find an overload for "Import" and the argument count: "2".
At C:\temp\test.ps1:36 char:9
+         $certificateObject.Import($CertificatePath, $sSecStrPassword);
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Can anyone help me sort this out?

Thanks to everyone. :-)

+8
source share
5 answers

According to this SuperUser answer in PS 3.0 there is a Get-PfxCertificate command for this:

 Get-PfxCertificate -FilePath Certificate.pfx 
+30
source

You can do it

$certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificateObject.Import($CertificatePath, $sSecStrPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
return $certificateObject.Thumbprint

Remember to set these two variables: $ CertificatePath and $ sSecStrPassword

+12
source

PowerShell . , . , , , - - X509KeyStorageFlags, .

$certificateObject.Import($CertificatePath, $sSecStrPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
+4

FYI, , Get-PfxCertificate PowerShell 6.0.

https://github.com/PowerShell/PowerShell-Docs/issues/2150

+1

: ? , :

    $thumbprint = (certutil -split -dump .\cert.pfx | findstr /c:"Cert Hash(sha1)").Substring(17)[-1]

PFX ,

    $thumbprint = (certutil -split -p the_secret_password_to_my_pfx -dump .\cert.pfx | findstr /c:"Cert Hash(sha1)").Substring(17)[-1]

Technically, this is not pure PowerShell, since it calls certutil.exe, but it should be on any Windows system, so it works.

+1
source

All Articles