public byte[] fromFile(File file) throws IOException { InputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); return fromInputStream(bis); } finally { LauncherUtils.close(bis); LauncherUtils.close(fis); } }
public byte[] fromZipContents(File file) throws IOException { SignatureList list = new SignatureList(); InputStream fis = null; ZipInputStream zip = null; try { fis = new FileInputStream(file); zip = new ZipInputStream(fis); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { list.add(entry.getName(), fromInputStream(zip)); } return list.toDigest(); } finally { LauncherUtils.close(zip); LauncherUtils.close(fis); } }
/** * Attempt to verify that a file is signed. * * @param in input stream * @param ext file extension * @throws SecurityException throw on verification failure * @throws IOException on I/O error */ public void verify(InputStream in, String ext) throws SecurityException, IOException { try { if (ext.equalsIgnoreCase("jar") || ext.equalsIgnoreCase("zip")) { verifyJar(in); } else { throw new SecurityException("Not sure how to verify the signature for '" + ext + "'"); } } finally { LauncherUtils.close(in); } }
/** * Attempt to verify that a Jar file is signed. All files (aside from ones in META-INF) must be * signed and trusted. * * @param in input stream * @throws SecurityException throw on verification failure * @throws IOException on I/O error */ @SuppressWarnings("resource") public void verifyJar(InputStream in) throws IOException { JarInputStream jarFile = null; try { jarFile = new JarInputStream(in); Manifest manifest = jarFile.getManifest(); if (manifest == null) { throw new SecurityException("The given file was not digitally signed"); } // Ensure all the entries' signatures verify correctly byte[] buffer = new byte[8192]; JarEntry entry; while ((entry = jarFile.getNextJarEntry()) != null) { if (entry.isDirectory()) continue; do {} while (jarFile.read(buffer, 0, buffer.length) != -1); Certificate[] certs = entry.getCertificates(); if (isMetaInf(entry.getName())) { continue; } else if (certs == null || certs.length == 0) { throw new SecurityException("The archive contains files that are not digitally signed"); } else { int i = 0; boolean verified = false; while (i < certs.length) { X509Certificate[] chain = findChain(certs, i); try { verify(chain); verified = true; break; } catch (SecurityException e) { } i += chain.length; } if (!verified) { throw new SecurityException( "The file(s) are signed by an entity that is not registered as 'trusted' with the launcher"); } } } } finally { LauncherUtils.close(jarFile); } }