Skip to content

Instantly share code, notes, and snippets.

@Riebart
Last active June 14, 2024 19:14
Show Gist options
  • Save Riebart/184f5762e6084d724c18bbac2027e665 to your computer and use it in GitHub Desktop.
Save Riebart/184f5762e6084d724c18bbac2027e665 to your computer and use it in GitHub Desktop.
Generate code signing certificate and key using Powershell
# Generate a new certificate with key, marked exportable (the default), suitable for code signing.
# The certificate is stored in the personal certificate store.
New-SelfSignedCertificate -Subject "CN={YOUR NAME}" -KeySpec "Signature" -KeyUsage "DigitalSignature" -KeyUsageProperty "Sign" -Friendlyname "Code Signing" -NotAfter $([datetime]::now.AddYears(5)) -Type "CodeSigningCert" -CertStoreLocation cert:\currentuser\my -KeyAlgorithm RSA -Keylength 4096 -HashAlgorithm "SHA256" -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider"
# To Sign a Powershell script with a certificate
# - Find the key, which you can usually do with the thumbprint and knowing where it was stored
# - This may or may not work for you, depending on whether or not you have access to a functioning timestamp server
# - Regardless of the timestamp, the signature will still work, just won't say when it was signed.
$cert = (ls cert:currentuser\my\0BD717BC985949E736067A15CC7502A1EAE6D031)
Set-AuthenticodeSignature .\script.ps1 $cert -TimestampServer http://freetsa.org/tsr -HashAlgorithm "SHA256"
@punk-t
Copy link

punk-t commented Jun 14, 2024

Set-AuthenticodeSignature is kinda weird with positional parameters. On my PS5.1 I always got an UnknownError status while in fact the script was signed actually.

When calling

Set-AuthenticodeSignature -FilePath .\script.ps1 $cert -TimestampServer http://freetsa.org/tsr -HashAlgorithm "SHA256"

the status changed to valid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment