2009-03-20 23 views
23

me gustaría comprobar mediante programación si un archivo ha sido firmado digitalmente o no.cómo comprobar si un archivo tiene una firma digital

Por el momento, he encontrado una bastante oscura code in MSDN, que no se compila ...

Alguna idea sobre el tema?

una herramienta externa con la línea de comandos también sería muy bueno, por cierto.

+0

Podría especificar un idioma en su pregunta, o estado que no le importa. Esto haría que sea más fácil responder. Gracias. –

+0

¿Por qué estás usando 2 cuentas llamadas Vinzz ??? –

+0

... y haciendo exactamente la misma pregunta ??? –

Respuesta

23

Descargue Sigcheck y use el siguiente comando.

sigcheck.exe -a -u -e 

Un ejemplo de un archivo DLL firmado

enter image description here

Un ejemplo de un archivo DLL sin firmar

enter image description here

Sigcheck es una utilidad de línea de comandos que muestra la versión del archivo número. Buena suerte

18

la parte que falta importante de la signtool mencionar respuesta es:

Sí, con el conocido signtool.exe También puede averiguar, si se firma un archivo. ¡No es necesario descargar otra herramienta!

E.g. con la línea simple:

signtool verify /pa myfile.exe 
if %ERRORLEVEL% GEQ 1 echo This file is not signed. 

(Para poner verbosa, agregue un '/ v' después '/ pa'.)

Uno puede preguntarse: ¿Por qué esto es importante? Solo firmo los archivos (nuevamente) que se firmarán y funcionarán.

Mi objetivo es mantener construye limpio, y no firme archivos una segunda vez porque se cambia no sólo la fecha, pero el binario es diferente después de eso.

Ejemplo de negocio: Mi cliente tiene un proceso simplificado de compilación tipo "dev ops" y post compilación. Existen múltiples fuentes para diferentes conjuntos de archivos, y al final todo está construido, probado y empaquetado de distribución- y de que algunos archivos tienen que ser firmado. Para garantizar que algunos archivos no salgan de la unidad sin haber sido firmados, solíamos firmar todos los archivos importantes, incluso si ya estaban firmados.

Pero esto no es lo suficientemente limpia:

1) Si firmamos un archivo nuevo, que ya está firmado, la fecha del archivo y cambios de huellas digitales binarias, y el archivo pierde la comparabilidad con él de las fuentes, si era simplemente copiado (Al menos si firma con una marca de tiempo, que siempre hacemos y creo que es muy recomendable)

Se trata de una pérdida de calidad grave, ya que este archivo ya no es comparable con sus predecesores de otro origen de archivo.

2) Si firmamos un archivo nuevo, esto también podría ser un fallo y es un archivo de terceros que no debe ser firmado por su unidad.

Usted puede evitar tanto al hacer la firma en sí condicional en función del código de retorno de la llamada anterior "SignTool verificar" que se menciona.

7

he encontrado otra opción (puro código .Net) en la web here.

el código es muy simple y funciona.

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Security.Cryptography.X509Certificates; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      string filePath = args[0]; 

      if (!File.Exists(filePath)) 
      { 
       Console.WriteLine("File not found"); 
       return; 
      } 

      X509Certificate2 theCertificate; 

      try 
      { 
       X509Certificate theSigner = X509Certificate.CreateFromSignedFile(filePath); 
       theCertificate = new X509Certificate2(theSigner); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("No digital signature found: " + ex.Message); 

       return; 
      } 

      bool chainIsValid = false; 

      /* 
    * 
    * This section will check that the certificate is from a trusted authority IE 
    * not self-signed. 
    * 
    */ 

      var theCertificateChain = new X509Chain(); 

      theCertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; 

      /* 
    * 
    * Using .Online here means that the validation WILL CALL OUT TO THE INTERNET 
    * to check the revocation status of the certificate. Change to .Offline if you 
    * don't want that to happen. 
    */ 

      theCertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Online; 

      theCertificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); 

      theCertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; 

      chainIsValid = theCertificateChain.Build(theCertificate); 

      if (chainIsValid) 
      { 
       Console.WriteLine("Publisher Information : " + theCertificate.SubjectName.Name); 
       Console.WriteLine("Valid From: " + theCertificate.GetEffectiveDateString()); 
       Console.WriteLine("Valid To: " + theCertificate.GetExpirationDateString()); 
       Console.WriteLine("Issued By: " + theCertificate.Issuer); 
      } 
      else 
      { 
       Console.WriteLine("Chain Not Valid (certificate is self-signed)"); 
      } 
     } 
    } 
} 
+1

Tenga en cuenta que esto recupera el certificado utilizado para firmar el archivo, pero NO verifica que el la firma del archivo es válida (es decir, si manipulas el archivo, este método seguirá devolviendo el firmante original, no te alertará sobre el hecho de que el archivo ha sido manipulado) –

-3

Seleccione <*>.exe haga clic derecho> propiedades. si el archivo está firmado, obtendrá esta pestaña en la ventana de propiedades de ese archivo.

property of the file

+0

No veo cómo esto ayuda a verificar "programáticamente" "si el archivo se está firmando digitalmente o no :) –

+1

esta respuesta realmente me ha ayudado – JerryGoyal

+0

Guau, esta respuesta es horrible. @JerryGoyal: la presencia de una firma digital ** no ** significa nada. ** ASEGÚRESE ** de que es válido yendo a Firmas digitales, seleccione firma, luego Detalles y compruebe que "Firma digital está OK" se muestra en la parte superior. – ahmd0

1

También se puede tratar de utilizar el paquete NPM sign-check para que los propósitos.

paquete que implementa la API WinVerifyTrust y tiene un uso sencillo:

npm install -g sign-check 

sign-check 'path/to/file' 
Cuestiones relacionadas