"Archivo de firma no válido" al intentar ejecutar a.jar


Mi programa java está empaquetado en un archivo jar y hace uso de una biblioteca jar externa, bouncy castle. Mi código compila bien, pero ejecutar el jar conduce al siguiente error:

Excepción en el hilo "main" java.lang.SecurityException: Resumen del archivo de firma no válido para los atributos principales del Manifiesto

He buscado en Google durante más de una hora buscando una explicación y he encontrado muy poco de valor. Si alguien ha visto este error antes y podría ofrecer algo de ayuda, estaría agradecido.

Author: Gray, 2009-06-16

17 answers

La solución listada aquí podría proporcionar un puntero.

Resumen del archivo de firma no válido para los atributos principales del Manifiesto

En pocas palabras:

Probablemente sea mejor mantener el frasco oficial como es y simplemente agregarlo como una dependencia en el archivo de manifiesto para su archivo jar de la aplicación.

 42
Author: Nrj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-03 21:51:10

Para aquellos que obtuvieron este error al intentar crear un uber-jar con maven-shade-plugin, la solución es excluir los archivos de firma de manifiesto agregando las siguientes líneas a la configuración del complemento:

<configuration>
    <filters>
        <filter>
            <artifact>*:*</artifact>
            <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
            </excludes>
        </filter>
    </filters>
    <!-- Additional configuration. -->
</configuration>
 934
Author: ruhsuzbaykus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

Para aquellos que usan gradle y tratan de crear y usar un frasco fat, la siguiente sintaxis podría ayudar.

jar {
    doFirst {
        from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' 
}
 114
Author: Keith P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-21 15:15:29

Algunas de sus dependencias son probablemente jarfiles firmados. Cuando se combinan todos en un gran archivo jarfile, los archivos de firma correspondientes siguen presentes, y ya no coinciden con el archivo jarfile "grande combinado", por lo que el tiempo de ejecución se detiene pensando que el archivo jar ha sido manipulado (que es...tiene por así decirlo).

Puede resolver el problema eliminando los archivos de firma de sus dependencias jarfile. Desafortunadamente, no es posible hacer esto en un solo paso ant .

Sin embargo, pude hacer que esto funcionara con Ant en dos pasos, sin nombrar específicamente cada dependencia de jarfile, usando:

<target name="jar" depends="compile" description="Create one big jarfile.">
    <jar jarfile="${output.dir}/deps.jar">
        <zipgroupfileset dir="jars">
            <include name="**/*.jar" />
        </zipgroupfileset>
    </jar>
    <sleep seconds="1" />
    <jar jarfile="${output.dir}/myjar.jar" basedir="${classes.dir}">
        <zipfileset src="${output.dir}/deps.jar" excludes="META-INF/*.SF" />
        <manifest>
            <attribute name="Main-Class" value="com.mycompany.MyMain" />
        </manifest>
    </jar>
</target>

El elemento sleep se supone que previene errores sobre archivos con fechas de modificación en el futuro.

Otras variaciones que encontré en los hilos enlazados no funcionaron para mí.

 53
Author: Rich Apodaca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:42

Utilice el siguiente comando

zip -d yourjar.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'
 38
Author: Peter2711,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-15 09:52:18

Tuve este problema al usar IntelliJ IDEA 14.01.

Pude arreglarlo por:

File - > Project Structure->Add New (Artifacts)->jar - > From Modules With Dependencies on the Create Jar From Module Window:

Seleccione su clase principal

Archivo JAR de Bibliotecas Seleccione copiar al directorio de salida y enlace a través de manifest

 22
Author: Travis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 18:07:46

La seguridad ya es un tema difícil, pero me decepciona ver que la solución más popular es eliminar las firmas de seguridad. JCE requiere estas firmas. Maven shade explota el archivo jar de BouncyCastle que coloca las firmas en META-INF, pero las firmas de BouncyCastle no son válidas para un nuevo uber-jar (solo para el jar de BC), y eso es lo que causa el error de firma no válida en este hilo.

Sí, excluyendo o eliminando las firmas como sugiere @ruhsuzbaykus de hecho hace que el error original desaparezca, pero también puede conducir a nuevos errores crípticos:

java.security.NoSuchAlgorithmException: PBEWithSHA256And256BitAES-CBC-BC SecretKeyFactory not available

Especificando explícitamente dónde encontrar el algoritmo de esta manera:

SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC","BC");

Pude obtener un error diferente:

java.security.NoSuchProviderException: JCE cannot authenticate the provider BC

JCE no puede autenticar al proveedor porque hemos eliminado las firmas criptográficas siguiendo la sugerencia en otra parte de este mismo hilo.

La solución que encontré fue el packer ejecutable complemento que utiliza un enfoque jar-in-jar para preservar la firma BouncyCastle en un único jar ejecutable.

ACTUALIZACIÓN :

Otra manera de hacer esto (¿la manera correcta?) es usarMaven Jar signer . Esto le permite seguir usando Maven shade sin obtener errores de seguridad. SIN embargo, debe tener un certificado de firma de código (Oracle sugiere buscar "Certificado de Firma de Código Java"). La configuración de POM se ve así:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <filters>
                    <filter>
                        <artifact>org.bouncycastle:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>your.class.here</mainClass>
                    </transformer>
                </transformers>
                <shadedArtifactAttached>true</shadedArtifactAttached>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jarsigner-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <id>sign</id>
            <goals>
                <goal>sign</goal>
            </goals>
        </execution>
        <execution>
            <id>verify</id>
            <goals>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <keystore>/path/to/myKeystore</keystore>
        <alias>myfirstkey</alias>
        <storepass>111111</storepass>
        <keypass>111111</keypass>
    </configuration>
</plugin>

No, no hay manera para que JCE reconozca un certificado autofirmado, por lo que si necesita preservar los certificados de BouncyCastle, debe usar el complemento jar-in-jar o obtener un certificado JCE.

 9
Author: MattW,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 22:16:47

Asumiendo que construyes tu archivo jar con ant, puedes simplemente indicarle a ant que omita el directorio META-INF. Esta es una versión simplificada de mi objetivo ant:

<jar destfile="app.jar" basedir="${classes.dir}">
    <zipfileset excludes="META-INF/**/*" src="${lib.dir}/bcprov-jdk16-145.jar"></zipfileset>
    <manifest>
        <attribute name="Main-Class" value="app.Main"/>
    </manifest>
</jar>
 8
Author: Kim Stebel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-05 07:02:07

Compare la carpeta META-INF en jar nuevo con jar antiguo (antes de agregar nuevas bibliotecas). Es posible que haya nuevos archivos. En caso afirmativo, puede eliminarlos. Debería ayudar. Respecto, 999michal

 2
Author: 999michal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-02 14:12:59

Error: Se ha producido un error de JNI, compruebe su instalación e inténtelo de nuevo Excepción en el hilo "main" java.lang.SecurityException: Resumen del archivo de firma no válido para los atributos principales del manifiesto al sol.seguridad.útil.SignatureFileVerifier.Processmpl (SignatureFileVerifier.java:314) al sol.seguridad.útil.SignatureFileVerifier.proceso(SignatureFileVerifier.java:268) en java.útil.frasco.JarVerifier.processEntry (JarVerifier.java:316) en Java.útil.frasco.JarVerifier.actualización(JarVerifier.java:228) en java.útil.frasco.JarFile.inicializeVerifier (JarFile.java:383) en java.útil.frasco.JarFile.getInputStream (JarFile.java: 450) al sol.misc.URLClassPath Jar JarLoader 2 2.getInputStream (URLClassPath.java: 977) al sol.misc.Recurso.cachedInputStream(Recurso.java:77) al sol.misc.Recurso.getByteBuffer(Recurso.java:160) en java.net.URLClassLoader.defineClass(URLClassLoader.java:454) en java.net.URLClassLoader.acceso$100(URLClassLoader.java:73) en java. net. URLClassLoader 1 1. ejecutar (URLClassLoader. java:368) en java. net. URLClassLoader 1 1. ejecutar (URLClassLoader. java:362) en java.seguridad.AccessController.doPrivileged(Método Nativo) en java.net.URLClassLoader.findClass(URLClassLoader.java:361) en java.lang.ClassLoader.loadClass (ClassLoader.java: 424) al sol.misc.Launcher App AppClassLoader.loadClass (Launcher.java:331) en Java.lang.ClassLoader.loadClass (ClassLoader.java:357) al sol.lanzador.LauncherHelper.checkAndLoadMain (LauncherHelper.java:495)

Lo que me ayudó (IntelliJ IDEA 2016.3): File - > Project Structure - > Artifacts - > Add JAR - > Select Main Class - > Choose "copy to the output directory and link via manifest" - > OK - > Apply - > Build - > Build Artifacts... - >Build

 2
Author: Little Fox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 09:16:14

Tuve un problema similar. La razón fue que estaba compilando usando un JDK con un JRE diferente al predeterminado en mi caja de Windows.

Usando el java correcto.exe resolvió mi problema.

 1
Author: Jus12,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-02 12:54:36

Es posible que dos firmantes diferentes estropeen la mente de Java.

Intente eliminar la carpeta META-INF del jar, agregar manifiesto y firmar JAR nuevamente, me ayudó: http://jehy.ru/articles/2013/12/13/invalid-signature-file-digest-for-manifest-main-attributes/

 1
Author: Jehy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-13 07:09:20

Una estrategia consistiría en usar ANT para simplificar la eliminación de la firma de cada archivo Jar. It would proceed with the following steps:

  1. Copiando el MANIFIESTO.MF en un archivo temporal
  2. Eliminando las entradas Name y SHA del archivo temporal
  3. Creando un archivo Jar temporal con el manifiesto temporal
  4. Eliminando el manifiesto temporal
  5. Intercambiar el archivo Jar original con el temporal

Aquí está una hormiga macrodef haciendo el trabajo:

<macrodef name="unsignjar" description="To unsign a specific Jar file">
    <attribute name="jarfile" 
        description="The jar file to unsign" />
    <sequential>
<!-- Copying to the temporary manifest file -->
        <copy toFile="@{jarFile}_MANIFEST.tmp">
            <resources>
                <zipentry zipfile="@{jarFile}" name="META-INF/MANIFEST.MF"/>
            </resources>
        </copy>
<!-- Removing the Name and SHA entries from the temporary file -->
        <replaceregexp file="@{jarFile}_MANIFEST.tmp" match="\nName:(.+?)\nSH" replace="SH" flags="gis" byline="false"/>
        <replaceregexp file="@{jarFile}_MANIFEST.tmp" match="SHA(.*)" replace="" flags="gis" byline="false"/>
<!-- Creating a temporary Jar file with the temporary manifest -->
        <jar jarfile="@{jarFile}.tmp"
            manifest="@{jarFile}_MANIFEST.tmp">
            <zipfileset src="@{jarFile}">
                <include name="**"/>
                <exclude name="META-INF/*.SF"/>
                <exclude name="META-INF/*.DSA"/>
                <exclude name="META-INF/*.RSA"/>
            </zipfileset>
        </jar>
<!-- Removing the temporary manifest -->
        <delete file="@{jarFile}_MANIFEST.tmp" />
<!-- Swapping the original Jar file with the temporary one -->
        <move file="@{jarFile}.tmp"
              tofile="@{jarFile}"
              overwrite="true" />
</sequential>

`

La definición se puede llamar así en una tarea ANT:

<target name="unsignJar">
    <unsignjar jarFile="org.test.myjartounsign.jar" />
</target>
 1
Author: bdulac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-26 15:32:33

Recientemente he comenzado a usar IntelliJ en mis proyectos. Sin embargo, algunos de mis colegas todavía usan Eclipse en los mismos proyectos. Hoy, tengo el mismo error después de ejecutar el archivo jar creado por mi IntelliJ. Mientras que todas las soluciones aquí hablando de casi la misma cosa, ninguna de ellas funcionó para mí fácilmente (posiblemente porque no uso ANT, maven build me dio otros errores que me referían a http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException , y también no podía averiguar cuáles son los frascos firmados por mí mismo!)

Finalmente, esto me ayudó

zip -d demoSampler.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'

¿Adivina qué se ha eliminado de mi archivo jar?!

deleting: META-INF/ECLIPSE_.SF 
deleting: META-INF/ECLIPSE_.RSA

Parece que el problema era relevante para algunos archivos relevantes para eclipse.

 1
Author: mhn_namak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-09 04:50:22

Si está obteniendo esto al intentar enlazar archivos JAR para un Xamarin.Android bindings project como así:

JARTOXML : advertencia J2XA006: error de clase faltante se planteó al reflejar com.su.class: Resumen del archivo de firma no válido para los atributos principales del Manifiesto

Simplemente abra los archivos JAR usando Winzip y elimine los directorios meta-inf. Reconstrucción-trabajo hecho

 0
Author: Dean Wild,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-23 09:30:06

En caso de que estés usando gradle, aquí tienes una tarea completa de farJar:

version = '1.0'
//create a single Jar with all dependencies
task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',  
            'Implementation-Version': version,
            'Main-Class': 'com.example.main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' 
    with jar
}
 0
Author: Nick De Greek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 14:27:37

Si está buscando una solución Fat JAR sin desempacar o manipular las bibliotecas originales, pero con un cargador de clases especial JAR, eche un vistazo a mi proyecto aquí.

Descargo de responsabilidad: yo no escribí el código, solo paquete y publicarlo en Maven Central y describir en mi lectura me cómo usarlo.

Lo uso personalmente para crear JARs uber ejecutables que contienen dependencias BouncyCastle. Tal vez sea útil para ti también.

 0
Author: kriegaex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-04 11:43:02