Code Signing Sertifikası ile Powershell İmzalama – How To Sign a Powershell Script with Code Signing Certificate

Powershell güvenlik açısından sadece localde imzalanan scriptlerin çalışması ayarları değiştirilmiş olabilir. Bu gibi durumlarda ortamda powershelleri imzalamak gerekiyor. Bunun için local sertifika sunucundan (certification Authority) CodeSigning sertifikası oluşturulmalıdır. Daha sonra aşağıdaki komutlar kullanılmalıdır.

Localde oluşan sertifikayı çekiyoruz. Bu sertifika local users alanında oluşmuştur.(certmgr.msc)

Maybe your computer has been configured to run PowerShell scripts. Therefore, you must sign your PowerShell scripts because they won’t run otherwise. You need to create a code-signing certificate from your Certificate Authority (CA). This certificate will be created in your local user certificate store. You can open the MMC panel to manage it, or you can open the ‘Run’ dialog, type certmgr.msc, and press Enter. Then, you have to use the following code:

$certificate = Get-ChildItem -Path Cert:* -Recurse -CodeSigningCert

Sertifika bilgilerini çektikten sonra aşağıdaki komutu kullanabiliriz. Powershell 7.3 versiyon sonrasında default Sha256 ile imzalanmaktadir. Bu yüzden HashAlgorithm zorunlu değil.

Powershel 7.3 support hashalgoritm default sha256. So, The HashAlgoritm don’t have to use when you sign a powershell script

# Generate a new self-signed code-signing certificate
$cert = New-SelfSignedCertificate -DnsName "YourDomainName" -Type CodeSigningCert -CertStoreLocation "Cert:\CurrentUser\My"

# Export the certificate to a PFX file (includes private key)
$certPath = "C:\path\to\your\certificate.pfx"
$certPassword = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
Export-PfxCertificate -Cert "Cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath $certPath -Password $certPassword

# Import the certificate into the trusted root store (optional but recommended)
Import-PfxCertificate -FilePath $certPath -CertStoreLocation "Cert:\CurrentUser\Root" -Password $certPassword

# Sign your PowerShell script
$scriptPath = "C:\path\to\your\script.ps1"
Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $cert
Set-AuthenticodeSignature -Certificate $certificate -FilePath C:\Powershell.ps1 -HashAlgorithm SHA256 -IncludeChain all