Search code examples
c#powershell.net-core

Sign a Powershellscript with C# / .NetCore


for my complex system i am looking for a way to sign a powershellscript not with powershell but with C# / .NetCore

here the Powershell version:

$cert=Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert
Set-AuthenticodeSignature -FilePath PsTestInternet2.ps1 -Certificate $cert

My current solution starts a Powershell console with

process.start

Why do I want to sign with C# and not Powershell?

  1. my system is an intranet service
  2. the user can compile a script from snippets in the app and select additional installation files
  3. now the script is signed and compiled with the installation files to an exe (C# console project - compiled at runtime with dotnet)
  4. this exe can be controlled by the user (the exe has switches to examine the update)
  5. now this exe (update) is distributed via wsus and arrives on user computers and installs the installation files with the script.

All this is a nice system, but it would be even nicer if I would not have to save the script first to sign it with

process-start => powershell

As you can read above I am not looking for someone to do my homework, but someone who is experienced enough to tell me how to sign the script with C# without using a powershellpipe.

Thanks a lot
Best regards


Solution

  • Now that I've invested more time and figured out the underlying technology, I found the solution on GitHub in Microsoft's code.

    Up to now it was also claimed here on stackoverflow that it is not possible.

    Here is, how they do it https://github.com/PowerShell/PowerShell/blob/d8f8f0a8bcbadb357f9eaafbb797278ebe07d7cc/src/System.Management.Automation/security/Authenticode.cs

    In this file you can find the signaturehelper class with the following function:

    internal static Signature SignFile(SigningOption option,
                                               string fileName,
                                               X509Certificate2 certificate,
                                               string timeStampServerUrl,
                                               string hashAlgorithm)
    

    Sorry if anyone minds, I found the solution so quickly. At least now I've shared it.

    Edit:

    Because of the underlying function, the file must still be saved first. So the advantage is marginal.