Search code examples
powershellcode-signing-certificate

Signing Assemblies using Certificate Thumprint using Powershell


What I want to achieve: I would like to sign my files using an existing Certificate Thumbprint.

I have an existing yml file that contains the following bit of code that is executed in a github workflow:

- name: Import signing cert
    shell: pwsh
    id: import_cert
    run: |
      $pfx = [System.Convert]::FromBase64String("${{ secrets.SIGNING_CERT }}")
      $certPath = '.\CompanyCertificate.pfx'
      [IO.File]::WriteAllBytes($certPath, $pfx)
      $certPass = ConvertTo-SecureString '${{ secrets.SIGNING_CERT_PASSWORD }}' -AsPlainText -Force
      Import-PfxCertificate -FilePath $certPath -CertStoreLocation Cert:\CurrentUser\My -Password $certPass
      $thumbprint = (Get-PfxCertificate -FilePath $certPath -Password $certPass).Thumbprint
      echo "::set-output name=THUMB_PRINT::$thumbprint"

I then loop through all the assemblies that need signing and try sign the assemblies(dlls and exes):

Write-Host "Signing assemblies"
      $filesToSign = Get-ChildItem -Path "${{ github.workspace }}\folder\Programs" -Include *.dll,*.exe -Recurse | 
        Get-AuthenticodeSignature | 
        Where-Object status -eq 'NotSigned'

        Set-AuthenticodeSignature -FilePath $filesToSign.path -Certificate '${{ steps.import_cert.outputs.THUMB_PRINT }}'

But I am getting the following error:

Cannot bind parameter 'Certificate'. Cannot convert value <"Certificate Thumbprint Redacted"> to type "System.Security.Cryptography.X509Certificates.X509Certificate2". Error: "The system cannot find the file specified."

Now I assume this is because I am trying to make use of the thumbprint from the certificate, which is gotten from my Import signing cert step, but this is existing code, so I dont want to change this.

My question: Can I sign my files using the Certificates Thumbprint ?

Thanks!


Solution

  • I found the solution. I needed to search for the Certificate based on the Thumbprint and then pass it through to the Set-AuthenticodeSignature:

    $cert = Get-ChildItem -path 'Cert:\*${{ steps.import_cert.outputs.THUMB_PRINT }}' -Recurse
    Set-AuthenticodeSignature -FilePath $filesToSign.path -Certificate $cert