.NET – Signing code with a certificate

You’re given .PFX code signing certificate and told to sign your code. What does this mean, and how do you do it?

What is code signing?

Signing code means creating a digital signature on an executable file by using a code signing certificate. When your code is executed, your organization’s security software will check that this executable was signed using the code signing certificate.

After you’ve signed an executable, you can see the digital signature in the file’s properties.

Digital signature on a DLL file produced by a code signing certificate

How do you sign code?

You can sign three types of files – .exe’s, .dll’s, and PowerShell scripts.

In the following examples, my code signing certificate is located at C:\HelloWorld\codesigningcert.pfx and has the password “1”.

Signing .exe’s and .dll’s

Execute the following on the command line:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\signtool.exe" sign /f "C:\HelloWorld\codesigningcert.pfx" /p 1 "C:\HelloWorld\HelloWorld.dll"Code language: Bash (bash)

After you’ve signed the file, you can check for the Digital Signature in the file’s properties.

Signing PowerShell scripts

Execute the following PowerShell:

$cert = Get-PfxCertificate -FilePath C:\HelloWorld\codesigningcert.pfx

Set-AuthenticodeSignature -FilePath C:\HelloWorld\HelloWorld.ps1 -Certificate $cert
Code language: PowerShell (powershell)

It’ll prompt you for the certificate password. Enter it and click OK.

PowerShell certificate password prompt

Open up your PowerShell script and verify that it has a signature block appended to it.

PowerShell script with a code signed signature block