DEV Community

Cover image for Sign files with powershell
bytewhisper
bytewhisper

Posted on

Sign files with powershell

Intro:

PowerShell offers a range of native cmdlets that allow us to sign and verify files without relying on external tools like Signtool.exe. In this step-by-step guide, we will explore how to use PowerShell to sign and verify digital files without using Signtool.exe. Additionally, we will delve into a section demonstrating how PowerShell can replace only the main certificate in a signature.

Note: Before proceeding, make sure you have a valid code signing certificate obtained from a trusted Certificate Authority (CA). Or visit my article: "How to create development certificate"

Press Win + X, then select "Windows PowerShell" or "Terminal" for windows 11, to open PowerShell.

To sign a file, we'll use the Set-AuthenticodeSignature cmdlet, which signs a file using the specified certificate.

$certificatePath = "C:\Path\To\Your\CodeSigningCertificate.pfx"
$certificatePassword = "your_certificate_password"
$fileToSign = "C:\Path\To\Your\File.exe"

$securePassword = ConvertTo-SecureString -String $certificatePassword -Force -AsPlainText
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certificatePath, $securePassword)

Set-AuthenticodeSignature -FilePath $fileToSign -Certificate $certificate
Enter fullscreen mode Exit fullscreen mode
  1. Replace "C:\Path\To\Your\CodeSigningCertificate.pfx" with the path to your code signing certificate.
  2. Replace "your_certificate_password" with the password for your certificate.
  3. Replace "C:\Path\To\Your\File.exe" with the path to the file you want to sign.

Verify the Signature

To verify the signature of the signed file, use the Get-AuthenticodeSignature cmdlet:

$signedFile = "C:\Path\To\Your\SignedFile.exe"
$signature = Get-AuthenticodeSignature -FilePath $signedFile

if ($signature.Status -eq "Valid")
{
    Write-Host "Signature is valid."
}
else
{
    Write-Host "Signature is not valid."
}
Enter fullscreen mode Exit fullscreen mode
  • Replace "C:\Path\To\Your\SignedFile.exe" with the path to the signed file.

Conclusion

PowerShell provides a powerful and native way to sign and verify digital files without the need for external tools like Signtool.exe. By leveraging PowerShell cmdlets, you can confidently sign your files and verify their authenticity and integrity. Always ensure that you keep your code signing certificates secure and protected to maintain the trust and integrity of your signed files.

Buy Me A Coffee

Top comments (0)