En mi aplicación, necesito verificar si está firmado o no. Si está firmado, continúe la ejecución y salga de la aplicación si no lo está. El letrero se usará para firmar la aplicación. ¿Hay algún código C# para hacer eso?Verificar si un ejecutable está firmado o no (signtool usado para firmar ese exe)
Respuesta
Aquí es un método de utilidad que lo hace:
var signed = IsSigned(@"c:\windows\explorer.exe");
...
public static bool IsSigned(string filePath)
{
if (filePath == null)
throw new ArgumentNullException(nameof(filePath));
var file = new WINTRUST_FILE_INFO();
file.cbStruct = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO));
file.pcwszFilePath = filePath;
var data = new WINTRUST_DATA();
data.cbStruct = Marshal.SizeOf(typeof(WINTRUST_DATA));
data.dwUIChoice = WTD_UI_NONE;
data.dwUnionChoice = WTD_CHOICE_FILE;
data.fdwRevocationChecks = WTD_REVOKE_NONE;
data.pFile = Marshal.AllocHGlobal(file.cbStruct);
Marshal.StructureToPtr(file, data.pFile, false);
int hr;
try
{
hr = WinVerifyTrust(INVALID_HANDLE_VALUE, WINTRUST_ACTION_GENERIC_VERIFY_V2, ref data);
}
finally
{
Marshal.FreeHGlobal(data.pFile);
}
return hr == 0;
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WINTRUST_FILE_INFO
{
public int cbStruct;
public string pcwszFilePath;
public IntPtr hFile;
public IntPtr pgKnownSubject;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct WINTRUST_DATA
{
public int cbStruct;
public IntPtr pPolicyCallbackData;
public IntPtr pSIPClientData;
public int dwUIChoice;
public int fdwRevocationChecks;
public int dwUnionChoice;
public IntPtr pFile;
public int dwStateAction;
public IntPtr hWVTStateData;
public IntPtr pwszURLReference;
public int dwProvFlags;
public int dwUIContext;
public IntPtr pSignatureSettings;
}
private const int WTD_UI_NONE = 2;
private const int WTD_REVOKE_NONE = 0;
private const int WTD_CHOICE_FILE = 1;
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private static readonly Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
[DllImport("wintrust.dll")]
private static extern int WinVerifyTrust(IntPtr hwnd, [MarshalAs(UnmanagedType.LPStruct)] Guid pgActionID, ref WINTRUST_DATA pWVTData);
Es muy complicado como solución, solo necesito un verdadero o falso: exe signed, exe no firmado –
No creo que tengas muchas opciones. La verificación de Authenticode no es tan fácil. Simplemente copie y pegue el código y llame a la última función: internal static uint WinVerifyTrust (string fileName). Un 0 devuelto significa que está firmado. –
@Anaseh como señaló Simon, la validación de la firma es más que solo verdadera o falsa. Debe determinar la presencia de la firma, su validez, luego la validez del certificado utilizado para hacer una firma, la validez de la marca de tiempo y el certificado utilizado para firmar una marca de tiempo. –
private bool IsAssemblySigned()
{
var assembly = Assembly.GetAssembly(GetType());
var assemblyName = assembly.GetName();
var key = assemblyName.GetPublicKey();
return key.Length > 0;
}
Muéstrese, le sugerí AssemblyName.GetPublicKey() http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.getpublickey%28VS.80% 29.aspx – pstrjds
Gracias por su respuesta, pero esta solución no funcionará porque no estoy usando la firma de ensamblaje, estoy usando signtool para firmar la aplicación –
yeas, signtool crea la firma de Authenticode, que no debe confundirse con .NET fuerte firma de clave de nombre. Ver mi respuesta a continuación. –
Yo sugeriría que utilice la API 'CryptUIWizDigitalSign'. This link se puede utilizar como referencia.
Try
Dim objCertificate As New Security.Cryptography.X509Certificates.X509Certificate2(Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile(strFile))
Return True
Catch ex As Exception
Return False
End Try
- 1. macro RAND_MAX: ¿firmado o sin firmar?
- 2. Un firmar un jar firmado
- 3. Tipo int predeterminado: ¿Firmado o sin firmar?
- 4. Firmado o sin firmar en MySQL
- 5. Para verificar si un objeto está vacío o no
- 6. ¿Qué lib o software para firmar y verificar a ciegas?
- 7. Macro para comprobar si un tipo entero está firmado o no
- 8. Embalaje un exe + DLL en un ejecutable (no .NET)
- 9. ¿Cómo puedo verificar si existe o no un recurso incrustado?
- 10. Java/Keystore Verificar Certificado firmado
- 11. Comprueba si un archivo no está abierto (no usado por otro proceso) en Python
- 12. Cómo verificar si un nombre eval no está definido
- 13. Cómo verificar un jar firmado con jarsigner programmatically
- 14. Comprueba si se está ejecutando un archivo exe específico
- 15. C++: falta de coincidencia firmado/no firmado cuando solo se usan tipos sin firmar
- 16. Cómo verificar que la marca de tiempo se hace correctamente para el código firmado
- 17. ¿Por qué un archivo ejecutable firmado digitalmente se tratará como no firmado hasta que se visualicen los detalles del certificado?
- 18. Cómo verificar si un archivo ejecutable o una DLL se compila en modo Liberar o Depurar (C++)
- 19. Cómo verificar si un DataGridViewCheckBoxCell está marcado
- 20. para verificar si todo EditText está vacío
- 21. alternativa para verificar, si un valor está en un conjunto
- 22. ¿Está mal usado static_cast?
- 23. está encriptado pero no firmado, ¿debilidad?
- 24. ¿Cómo verificar si un objeto está definido?
- 25. ¿Cómo verificar programáticamente que un ensamble esté firmado con un certificado específico?
- 26. Verificar si Solidworks está instalado?
- 27. Para comprobar si la sesión está disponible o no
- 28. Python: compruebe si un archivo está vacío o no
- 29. ¿Intenta capturar el ejecutable exe en Powershell?
- 30. compruebe si un dominio está disponible o no usando PHP?
¿Qué está utilizando para firmar la aplicación? – Lazarus
En realidad, estoy usando signtool. –