gpt4 book ai didi

java - 如何以编程方式验证使用 jarsigner 签名的 jar

转载 作者:IT老高 更新时间:2023-10-28 20:28:29 29 4
gpt4 key购买 nike

我想使用 jarsigner 对 jar 进行签名,然后使用 Java 应用程序对其进行验证,该应用程序没有将签名的 jar 作为其类路径的一部分(即仅使用 jar 的文件系统位置)

现在我的问题是从 jar 中取出签名文件,有没有简单的方法可以做到这一点?

我玩过 Inflater 和 Jar InputStreams,但没有运气。

或者这是可以以更好的方式完成的事情吗?

谢谢

最佳答案

您可以简单地使用 java.util.jar.JarFile 打开 JAR 并告诉它验证 JAR 文件。如果 JAR 已签名,则 JarFile 可以选择验证它(默认情况下启用)。但是,JarFile 也会愉快地打开未签名的 JAR,因此您还必须检查文件是否已签名。您可以通过检查 JAR list 中的 *-Digest 属性来做到这一点:具有此类属性属性的元素已签名。

例子:

JarFile jar = new JarFile(new File("path/to/your/jar-file"));

// This call will throw a java.lang.SecurityException if someone has tampered
// with the signature of _any_ element of the JAR file.
// Alas, it will proceed without a problem if the JAR file is not signed at all
InputStream is = jar.getInputStream(jar.getEntry("META-INF/MANIFEST.MF"));
Manifest man = new Manifest(is);
is.close();

Set<String> signed = new HashSet();
for(Map.Entry<String, Attributes> entry: man.getEntries().entrySet()) {
for(Object attrkey: entry.getValue().keySet()) {
if (attrkey instanceof Attributes.Name &&
((Attributes.Name)attrkey).toString().indexOf("-Digest") != -1)
signed.add(entry.getKey());
}
}

Set<String> entries = new HashSet<String>();
for(Enumeration<JarEntry> entry = jar.entries(); entry.hasMoreElements(); ) {
JarEntry je = entry.nextElement();
if (!je.isDirectory())
entries.add(je.getName());
}

// contains all entries in the Manifest that are not signed.
// Ususally, this contains:
// * MANIFEST.MF itself
// * *.SF files containing the signature of MANIFEST.MF
// * *.DSA files containing public keys of the signer

Set<String> unsigned = new HashSet<String>(entries);
unsigned.removeAll(signed);

// contains all the entries with a signature that are not present in the JAR
Set<String> missing = new HashSet<String>(signed);
missing.removeAll(entries);

关于java - 如何以编程方式验证使用 jarsigner 签名的 jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374170/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com