Example usage for java.util.jar JarEntry getCertificates

List of usage examples for java.util.jar JarEntry getCertificates

Introduction

In this page you can find the example usage for java.util.jar JarEntry getCertificates.

Prototype

public Certificate[] getCertificates() 

Source Link

Document

Returns the Certificate objects for this entry, or null if none.

Usage

From source file:com.bbxiaoqu.api.util.Utils.java

/**
 * ???MD5/*  w  ww  . j a v a  2s. c  om*/
 */
public static String getFileSignatureMd5(String targetFile) {

    try {
        JarFile jarFile = new JarFile(targetFile);
        // ?RSA
        JarEntry jarEntry = jarFile.getJarEntry("AndroidManifest.xml");

        if (jarEntry != null) {
            InputStream is = jarFile.getInputStream(jarEntry);
            byte[] buffer = new byte[8192];
            while (is.read(buffer) > 0) {
                // do nothing
            }
            is.close();
            Certificate[] certs = jarEntry == null ? null : jarEntry.getCertificates();
            if (certs != null && certs.length > 0) {
                String rsaPublicKey = String.valueOf(certs[0].getPublicKey());
                return getMD5(rsaPublicKey);
            }
        }
    } catch (IOException e) {
        W("occur IOException when get file signature", e);
    }
    return "";
}

From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;/*w w  w.j a  va  2 s  . co m*/
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {

            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info(
                            "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {

                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s",
                                fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e,
                    "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe(
                "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",
                codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe(
                    "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe(
                    "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, "
                            + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so "
                            + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY "
                            + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe(
                    "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe(
                    "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it",
                    codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException {
    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(pathName);
    InputStream input = jarFile.getInputStream(entry);
    byte[] classData = new byte[(int) entry.getSize()];
    int totalBytes = 0;
    while (totalBytes < classData.length) {
        int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes);
        if (bytesRead == -1) {
            throw new IOException("Jar Entry too short!");
        }//from   w ww .  j  ava2  s.  c o  m
        totalBytes += bytesRead;
    }
    Class<?> loadedClass = defineClass(name, classData, 0, classData.length,
            new CodeSource(url, entry.getCertificates()));
    input.close();
    jarFile.close();
    return loadedClass;
}

From source file:JNLPAppletLauncher.java

/**
 * Check the native certificates with the ones in the jar file containing the
 * certificates for the JNLPAppletLauncher class (all must match).
 *//* w  w w  .  j  a v a2 s  . co  m*/
private boolean checkNativeCertificates(JarFile jar, JarEntry entry, byte[] buf) throws IOException {

    // API states that we must read all of the data from the entry's
    // InputStream in order to be able to get its certificates

    InputStream is = jar.getInputStream(entry);
    int totalLength = (int) entry.getSize();
    int len;
    while ((len = is.read(buf)) > 0) {
    }
    is.close();

    // locate JNLPAppletLauncher certificates
    Certificate[] appletLauncherCerts = JNLPAppletLauncher.class.getProtectionDomain().getCodeSource()
            .getCertificates();
    if (appletLauncherCerts == null || appletLauncherCerts.length == 0) {
        throw new IOException("Cannot find certificates for JNLPAppletLauncher class");
    }

    // Get the certificates for the JAR entry
    Certificate[] nativeCerts = entry.getCertificates();
    if (nativeCerts == null || nativeCerts.length == 0) {
        return false;
    }

    int checked = 0;
    for (int i = 0; i < appletLauncherCerts.length; i++) {
        for (int j = 0; j < nativeCerts.length; j++) {
            if (nativeCerts[j].equals(appletLauncherCerts[i])) {
                checked++;
                break;
            }
        }
    }
    return (checked == appletLauncherCerts.length);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find specified resource in local repositories.
 *
 * @return the loaded resource, or null if the resource isn't found
 *//* w ww  .  ja v a 2s  .  co m*/
protected ResourceEntry findResourceInternal(String name, String path) {

    if (!started) {
        log.info(sm.getString("webappClassLoader.stopped"));
        return null;
    }

    if ((name == null) || (path == null))
        return null;

    ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
    if (entry != null)
        return entry;

    int contentLength = -1;
    InputStream binaryStream = null;

    int jarFilesLength = jarFiles.length;
    int repositoriesLength = repositories.length;

    int i;

    Resource resource = null;

    for (i = 0; (entry == null) && (i < repositoriesLength); i++) {
        try {

            String fullPath = repositories[i] + path;

            Object lookupResult = resources.lookup(fullPath);
            if (lookupResult instanceof Resource) {
                resource = (Resource) lookupResult;
            }

            // Note : Not getting an exception here means the resource was
            // found
            if (securityManager != null) {
                PrivilegedAction dp = new PrivilegedFindResource(files[i], path);
                entry = (ResourceEntry) AccessController.doPrivileged(dp);
            } else {
                entry = findResourceInternal(files[i], path);
            }

            ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath);
            contentLength = (int) attributes.getContentLength();
            entry.lastModified = attributes.getLastModified();

            if (resource != null) {

                try {
                    binaryStream = resource.streamContent();
                } catch (IOException e) {
                    return null;
                }

                // Register the full path for modification checking
                // Note: Only syncing on a 'constant' object is needed
                synchronized (allPermission) {

                    int j;

                    long[] result2 = new long[lastModifiedDates.length + 1];
                    for (j = 0; j < lastModifiedDates.length; j++) {
                        result2[j] = lastModifiedDates[j];
                    }
                    result2[lastModifiedDates.length] = entry.lastModified;
                    lastModifiedDates = result2;

                    String[] result = new String[paths.length + 1];
                    for (j = 0; j < paths.length; j++) {
                        result[j] = paths[j];
                    }
                    result[paths.length] = fullPath;
                    paths = result;

                }

            }

        } catch (NamingException e) {
        }
    }

    if ((entry == null) && (notFoundResources.containsKey(name)))
        return null;

    JarEntry jarEntry = null;

    synchronized (jarFiles) {

        openJARs();
        for (i = 0; (entry == null) && (i < jarFilesLength); i++) {

            jarEntry = jarFiles[i].getJarEntry(path);

            if (jarEntry != null) {

                entry = new ResourceEntry();
                try {
                    entry.codeBase = getURL(jarRealFiles[i]);
                    String jarFakeUrl = getURI(jarRealFiles[i]).toString();
                    jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
                    entry.source = new URL(jarFakeUrl);
                    entry.lastModified = jarRealFiles[i].lastModified();
                } catch (MalformedURLException e) {
                    return null;
                }
                contentLength = (int) jarEntry.getSize();
                try {
                    entry.manifest = jarFiles[i].getManifest();
                    binaryStream = jarFiles[i].getInputStream(jarEntry);
                } catch (IOException e) {
                    return null;
                }

                // Extract resources contained in JAR to the workdir
                if (!(path.endsWith(".class"))) {
                    byte[] buf = new byte[1024];
                    File resourceFile = new File(loaderDir, jarEntry.getName());
                    if (!resourceFile.exists()) {
                        Enumeration entries = jarFiles[i].entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry2 = (JarEntry) entries.nextElement();
                            if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith(".class"))) {
                                resourceFile = new File(loaderDir, jarEntry2.getName());
                                // No need to check mkdirs result because an
                                // IOException will occur anyway
                                resourceFile.getParentFile().mkdirs();
                                FileOutputStream os = null;
                                InputStream is = null;
                                try {
                                    is = jarFiles[i].getInputStream(jarEntry2);
                                    os = new FileOutputStream(resourceFile);
                                    while (true) {
                                        int n = is.read(buf);
                                        if (n <= 0) {
                                            break;
                                        }
                                        os.write(buf, 0, n);
                                    }
                                } catch (IOException e) {
                                    // Ignore
                                } finally {
                                    try {
                                        if (is != null) {
                                            is.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                    try {
                                        if (os != null) {
                                            os.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

        if (entry == null) {
            synchronized (notFoundResources) {
                notFoundResources.put(name, name);
            }
            return null;
        }

        if (binaryStream != null) {

            byte[] binaryContent = new byte[contentLength];

            try {
                int pos = 0;

                while (true) {
                    int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos);
                    if (n <= 0)
                        break;
                    pos += n;
                }
                binaryStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            entry.binaryContent = binaryContent;

            // The certificates are only available after the JarEntry 
            // associated input stream has been fully read
            if (jarEntry != null) {
                entry.certificates = jarEntry.getCertificates();
            }

        }

    }

    // Add the entry in the local resource repository
    synchronized (resourceEntries) {
        // Ensures that all the threads which may be in a race to load
        // a particular class all end up with the same ResourceEntry
        // instance
        ResourceEntry entry2 = (ResourceEntry) resourceEntries.get(name);
        if (entry2 == null) {
            resourceEntries.put(name, entry);
        } else {
            entry = entry2;
        }
    }

    return entry;

}