I was able to sign a js file with PowerShell Set-AuthenticodeSignature. After that i can see signature appeared in file in form of:
// SIG // Begin signature blo
I recently encountered similar problem and let me show what I did to solve this problem. Before I go , there are few assumptions I make now. Please correct me if I am wrong.
I figured it out this happens only with script files as I have mentioned above because wintrust behaves wierdly when its methods are being executed from free-threaded apartment model (MTA). Once it's been wrapped inside a STA thread, it started working for me. Later I came to know it is a historical issue that we should have taken a precaution when we deal with any COM components interoperations from .Net application.
Here is the code snippet, you can replace the verifysignature with your wintrust code logic and try. I hope this helps.
public static void CheckSignature()
{
STAApartment apt = new STAApartment();
var result = apt.Invoke(() =>
{
return VerifySignature(@".\signedjsfile.js", false);
});
Console.WriteLine(result);
}
private static WinVerifyTrustResult VerifySignature(string filePath, bool verifySignatureOnly)
{
using (var wtd = new WinTrustData(new WinTrustFileInfo(filePath))
{
dwUIChoice = WintrustUIChoice.WTD_UI_NONE,
dwUIContext = WinTrustDataUIContext.WTD_DATA_UI_EXECUTE,
fdwRevocationChecks = WinTrustDataRevocationChecks.WTD_REVOCATION_CHECK_WHOLECHAIN,
dwStateAction = WintrustAction.WTD_STATEACTION_IGNORE,
dwProvFlags = verifySignatureOnly ? WintrustProviderFlags.WTD_HASH_ONLY_FLAG : WintrustProviderFlags.WTD_REVOCATION_CHECK_CHAIN
})
{
var result = WinTrust.WinVerifyTrust(
WinTrust.INVALID_HANDLE_VALUE, new Guid(WinTrust.WINTRUST_ACTION_GENERIC_VERIFY_V2), wtd
);
return result;
}
}
public class STAApartment
{
public T Invoke(Func func)
{
var tcs = new TaskCompletionSource();
Thread thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task.Result;
}
}